File Operations in C Language: Opening, Reading, Writing, and Closing Files

File Operations in C Language: Opening, Reading, Writing, and Closing Files

In C language, file operations are a very important topic. Through file operations, we can persist data to disk or read data from disk. This article will detail how to open, read, write, and close files in C language.

1. File Pointer

Before performing any file operations, we need to understand a concept—file pointer. In C language, the <span>FILE</span> type is used to represent a file stream, and we typically use <span>FILE *fp;</span> to define a pointer to this type.

2. Opening a File

To operate on a file, we first need to open it. In C language, the <span>fopen()</span> function can be used to open a file. Its basic syntax is as follows:

FILE *fopen(const char *filename, const char *mode);
  • <span>filename</span>: The name of the file to be opened.
  • <span>mode</span>: The file access mode, such as read-only, write, etc.

Common modes include:

  • <span>"r"</span>: Opens a text file for reading only.
  • <span>"w"</span>: Creates or overwrites a text file for writing.
  • <span>"a"</span>: Opens a text file for appending.
  • <span>"rb"</span>, <span>"wb"</span>, <span>"ab"</span>: Correspond to read, write, and append modes in binary format.

Example Code: Open and Check for Success

#include <stdio.h>
int main() {
    FILE *fp;
    fp = fopen("example.txt", "r"); // Attempt to open example.txt in read-only mode
    if (fp == NULL) {
        perror("Error opening file");
        return -1;
    }
    printf("File opened successfully.\n");
    fclose(fp); // Don't forget to close the opened file
    return 0;
}

3. Writing Data to a File

If we want to write data to a newly created or existing text/binary document, we can use the <span>fprintf()</span> or <span>fwrite()</span> functions.

Using fprintf()

<span>fprintf()</span> is used for formatted output to a specified stream (such as text).

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

Example Code: Write Data to a Text File

#include <stdio.h>
int main() {
    FILE *fp;
    fp = fopen("output.txt", "w"); // Create and open output.txt for writing
    if (fp == NULL) {
        perror("Error opening file");
        return -1;
    }
    fprintf(fp, "Hello, World!\n"); // Write string to output.txt
    fclose(fp); // Close the completed document
    return 0;
}

Using fwrite()

<span>fwrite()</span> is used to directly output the contents from memory (such as structures) to a binary stream.

size_t fwrite(const void *ptr, size_t size, size_t count, FILE *stream);

Example Code: Write Data to a Binary Document

#include <stdio.h>
int main() {
    FILE *fp;
    int numbers[] = {1, 2, 3, 4};
    fp = fopen("numbers.bin", "wb"); // Create and open in binary mode
    if (fp == NULL) {
        perror("Error opening file");
        return -1;
    }
    fwrite(numbers, sizeof(int), sizeof(numbers)/sizeof(numbers[0]), fp); // Output array contents to binary file
    fclose(fp);
    return 0;
}

4. Reading Data from a File

To read existing data, we can use the <span>fscanf()</span> and <span>fread()</span> functions.

Using fscanf()

<span>fscanf()</span> is used to read formatted input from a specified stream (such as text).

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

Example Code: Read Data from a Text Document

#include <stdio.h>
int main() {
    FILE* fp;
    char str[100];
    fp = fopen("output.txt", "r"); // Open the previously created data document
    if (fp == NULL) {
        perror("Error opening file");
        return -1;
    }
    fscanf(fp, "%s", str); // Read string from output.txt
    printf("%s\n", str);
    fclose(fp);
    return 0;
}

Using fread()

<span>fread()</span> is used to directly read memory contents from a binary stream.

Example Code: Read Data from a Binary Document

#include <stdio.h>
int main() {
    FILE* fp;
    int numbers[4];
    fp = fopen("numbers.bin", "rb");
    if (fp == NULL) {
        perror("Error opening file");
        return -1;
    }
    fread(numbers, sizeof(int), 4, fp); // Retrieve four integers from binary document
    for(int i=0; i<4; i++) {
        printf("%d ", numbers[i]);
    }
    fclose(fp);
    return 0;
}

Conclusion

This article introduced the importance and basic methods of file operations in C language, including how to effectively open, write, and extract information from text and binary documents using different functions. These skills are essential and highly practical in actual development processes, and I hope everyone can master these foundational knowledge and apply them flexibly in their own projects.

Leave a Comment