Various Methods and Examples of File Read and Write Operations in C Language

Various Methods and Examples of File Read and Write Operations in C Language

In C language, file read and write operations are one of the important basic operations. Through files, we can persistently store data on disk or read data from the disk. In this article, we will detail several main methods for performing file operations in C, including how to open, read, write, and close files. We will also provide example code to aid understanding.

File Pointer and Opening Files

Before performing any file operations, we need a <span>FILE</span> type pointer to represent the file. We can use the <span>fopen()</span> function to open a file, with the following syntax:

FILE *fopen(const char *filename, const char *mode);
  • <span>filename</span> is the name of the file to be opened.
  • <span>mode</span> specifies how to open the file; it is a string that can be one of the following modes:
    • <span>"r"</span>: Opens a text file in read-only mode; returns NULL on failure.
    • <span>"w"</span>: Creates an empty text file and opens it in write mode, which will overwrite an existing file with the same name.
    • <span>"a"</span>: Opens a file for appending content at the end of an existing text file.

Below is example code demonstrating how to open and close a file:

#include <stdio.h>
int main() {
    FILE *file;
    // Open a text file for reading
    file = fopen("example.txt", "r");
    if (file == NULL) {
        printf("Cannot open the specified file!\n");
        return -1;
    }
    // Perform other read/write operations here...
    // Close the file when no longer needed
    fclose(file);
    return 0;
}

File Read Operations

We can use various functions to read data from an already opened file, commonly used functions include:

Using fgetc()

<span>fgetc()</span> is used to read a single character from the specified file. The function returns EOF when it encounters EOF.

int fgetc(FILE *stream);

Example:

#include <stdio.h>
int main() {
    FILE *file;
    file = fopen("example.txt", "r");
    if (file == NULL) {
        printf("Cannot open the file\n");
        return -1;
    }
    int ch;
    while ((ch = fgetc(file)) != EOF) { // Loop until end-of-file.
        putchar(ch); // Output each character.
    }
    fclose(file); // Close the file
    return 0;
}

Using fgets()

<span>fgets()</span> can read a line of characters from the input stream and store it in an array. It is typically used for line-by-line processing of text.

char *fgets(char *str, int n, FILE *stream);

Example:

#include <stdio.h>
int main() {
    FILE *file;
    char buffer[100]; // Set line buffer size to 100
    file = fopen("example.txt", "r");
    if (file == NULL) {
        printf("Cannot open the file\n");
        return -1;
    }
    while (fgets(buffer, sizeof(buffer), file)) {
        printf("%s", buffer); // Output each line of characters
    }
    fclose(file);
    return 0;
}

File Write Operations

For writing data to a file, there are different methods for creating or appending content, as described below:

Using fputc()

<span>fputc()</span> writes a single character to the output stream of the specified file.

int fputc(int c, FILE *stream);

Example:

#include <stdio.h>
int main() {
    FILE* file;
    file = fopen("output.txt", "w");
    if (file == NULL) {
        printf("Cannot open the file!\n");
        return -1;
    }
    for (char ch='A'; ch <= 'Z'; ch++) {
        fputc(ch, file);
    }
    fclose(file);
    return 0;
}

Using fprintf()

Similar to standard output,<span>fprintf()</span> can perform formatted output, writing strings or various formatted data to the specified output stream (such as a file).

int fprintf(FILE* stream, const char* format,...);

Example:

#include <stdio.h>
int main() {
    FILE* fk;
    fk = fopen ("output.txt","w");
    if(fk==NULL){
        printf ("Cannot open the output text.\n");
        return -1;
    }
    for(int j=0;j<10;j++){
        fprintf(fk,"Line %d\n", j+1);
    }
    fclose(fk);
    return(0);
}

Conclusion

This article briefly introduces the basic methods of reading and writing files in the C programming language. We learned how to use <span>fopen()</span> to open files, and various methods (<span>fgetc()</span>, <span>fgets()</span>, <span>fprintf()</span>) to extract and place data within files. Additionally, enhancing flexibility by performing error checks on these functions can improve program robustness. We hope this article helps you understand and learn C language file operations.

Leave a Comment