Advertisement

Responsive Advertisement

File I/O in c

 Learning Sections          show

File I/O in C

Example


#include<stdio.h>  // Include the standard input-output library

int main() {
    // File pointer declaration
    FILE *filePointer;

    // Open a file in write mode
    filePointer = fopen("example.txt", "w");

    // Check if the file opened successfully
    if (filePointer == NULL) {
        printf("File failed to open.\n");
        return 1;
    }

    // Write data to the file
    fprintf(filePointer, "Hello, File I/O in C!");

    // Close the file
    fclose(filePointer);

    // Reopen the file in read mode
    filePointer = fopen("example.txt", "r");

    // Check if the file opened successfully
    if (filePointer == NULL) {
        printf("File failed to open.\n");
        return 1;
    }

    // Read data from the file
    char buffer[255];
    fgets(buffer, 255, filePointer);
    printf("Data from file: %s", buffer);

    // Close the file
    fclose(filePointer);

    return 0;
}
    

Explanation:

File I/O in C involves operations such as opening, reading, writing, and closing files. It is essential for handling data persistence and file manipulation.

In this example:

  • #include<stdio.h>: Includes the standard input-output library which provides functions for file I/O operations.
  • FILE *filePointer;: Declares a file pointer variable.
  • filePointer = fopen("example.txt", "w");: Opens a file named example.txt in write mode. If the file does not exist, it will be created.
  • if (filePointer == NULL): Checks if the file was opened successfully. If not, an error message is printed and the program exits.
  • fprintf(filePointer, "Hello, File I/O in C!");: Writes the string "Hello, File I/O in C!" to the file.
  • fclose(filePointer);: Closes the file.
  • filePointer = fopen("example.txt", "r");: Reopens the file in read mode.
  • char buffer[255];: Declares a buffer to store data read from the file.
  • fgets(buffer, 255, filePointer);: Reads data from the file into the buffer.
  • printf("Data from file: %s", buffer);: Prints the data read from the file to the console.
  • fclose(filePointer);: Closes the file.
  • return 0;: Ends the main function and returns 0 to the operating system, indicating that the program ended successfully.

In summary, file I/O in C allows you to work with files for reading and writing data, which is crucial for many applications that require data persistence and file manipulation.