» Quick Introduction to C » 2. Advanced » 2.1 File I/O

File I/O

In C, the FILE structure is a data structure defined in the standard I/O library to handle file input and output. The FILE structure is an abstraction that represents a file stream, providing the necessary information and control for performing file-related operations. It is typically used with functions such as fopen, fclose, fread, fwrite, fseek, etc.

If you want to copy the content of file source.txt into file destination.txt, you can do this:

#include <stdio.h>

int main() {
    FILE *sourceFile, *destinationFile;
    char buffer[1024];
    size_t bytesRead;

    // Open the source file in binary read mode
    sourceFile = fopen("source.txt", "rb");

    // Check if the source file exists
    if (sourceFile == NULL) {
        printf("Error opening source file.\n");
        return 1;
    }

    // Open the destination file in binary write mode
    destinationFile = fopen("destination.txt", "wb");

    // Check if the destination file was created successfully
    if (destinationFile == NULL) {
        printf("Error creating destination file.\n");

        // Close the source file before exiting
        fclose(sourceFile);

        return 2;
    }

    // Copy the contents of the source file to the destination file using fwrite
    while ((bytesRead = fread(buffer, 1, sizeof(buffer), sourceFile)) > 0) {
        fwrite(buffer, 1, bytesRead, destinationFile);
    }

    // Close both files
    fclose(sourceFile);
    fclose(destinationFile);

    return 0;
}