FILE HANDLING IN C-SAMPLE



File Handling Sample Program


#include <stdio.h>

int main() {
    FILE *fptr;
    char name[50], content[100];

    // Open file for reading (mode "r")
    fptr = fopen("data.txt", "r");

    // Check if file opened successfully
    if (fptr == NULL) {
        printf("Error! Could not open file.\n");
        return 1;
    }

    // Read content from file (assuming it's formatted with name followed by a newline and then content)
    fscanf(fptr, "%s\n", name);
    fgets(content, 100, fptr);

    // Close the file
    fclose(fptr);

    printf("Name read from file: %s\n", name);
    printf("Content read from file: %s\n", content);

    // Open file for writing (mode "w" will overwrite existing content)
    fptr = fopen("data.txt", "w");

    // Check if file opened successfully
    if (fptr == NULL) {
        printf("Error! Could not open file.\n");
        return 1;
    }

    // Write new content to the file
    printf("Enter a name: ");
    fgets(name, 50, stdin); // Read name from user input
    printf("Enter some content: ");
    fgets(content, 100, stdin); // Read content from user input
    fprintf(fptr, "%s\n%s", name, content);

    // Close the file
    fclose(fptr);

    printf("Data written to file successfully.\n");

    return 0;
}

This program first opens a file named "data.txt" in read mode ("r"). It then reads the name and content from the file using fscanf and fgets functions. After reading, it closes the file and displays the retrieved data.

In the second part, the program opens the same file in write mode ("w"). This will overwrite any existing content. It then prompts the user for a name and some content, reads them using fgets, and writes them to the file using fprintf. Finally, it closes the file and displays a success message.

Explanation of Key Functions:

  • fopen(filename, mode): Opens a file with the specified name and mode ("r" for reading, "w" for writing, etc.). Returns a pointer to the file if successful, otherwise NULL.
  • fscanf(fptr, format, ...): Reads formatted data from a file (similar to scanf but for files).
  • fgets(buffer, size, fptr): Reads a line of text from a file into the specified buffer.
  • fprintf(fptr, format, ...): Writes formatted data to a file (similar to printf but for files).
  • fclose(fptr): Closes the specified file.

This is a basic example, and C offers various other functions for more advanced file handling operations.

Post a Comment

0 Comments