MCS-011 Problem Solving and Programming

First year, Semester 1

Chapters

Newsletter

File Handling

File handling in C is accomplished using file pointers, which provide a way to access and manipulate files. A file pointer is a variable of type FILE*, used to keep track of the position within the file and manage file operations.


Basic Steps for File Handling

  1. Declare a File Pointer:

    FILE *fp;
  2. Open a File: Use the fopen function to open a file. It returns a file pointer or NULL if the operation fails.

    fp = fopen("filename.txt", "mode");

    Common modes include:

    • "r": Read (file must exist)
    • "w": Write (creates a new file or truncates existing file)
    • "a": Append (writes data to the end of the file)
    • "r+": Read/Write (file must exist)
    • "w+": Read/Write (creates a new file or truncates existing file)
    • "a+": Read/Write (writes data to the end of the file)
  3. Perform File Operations: Use various functions to read from or write to the file.

    • Writing to a File:

      fprintf(fp, "format", data);
      fputc('c', fp); fputs("string", fp);
    • Reading from a File:

      fscanf(fp, "format", &data);
      char c = fgetc(fp); char str[100]; fgets(str, 100, fp);
  4. Close the File: Use fclose to close the file and release resources.

    fclose(fp);

Example

Here's a complete example of writing to and reading from a text file using file pointers.

#include <stdio.h>
int main() { FILE *fp; // Open a file for writing fp = fopen("example.txt", "w"); if (fp == NULL) { printf("Error opening file for writing!\n"); return 1; } // Write to the file fprintf(fp, "Hello, World!\n"); fputs("This is a file handling example.\n", fp); // Close the file fclose(fp); // Open the file for reading fp = fopen("example.txt", "r"); if (fp == NULL) { printf("Error opening file for reading!\n"); return 1; } // Read from the file char buffer[255]; while (fgets(buffer, sizeof(buffer), fp) != NULL) { printf("%s", buffer); } // Close the file fclose(fp); return 0; }

File Operations Summary

  • fopen: Opens a file and returns a file pointer.
  • fclose: Closes a file.
  • fprintf, fputs, fputc: Write data to a file.
  • fscanf, fgets, fgetc: Read data from a file.
  • feof: Checks if the end of the file is reached.
  • ferror: Checks for file operation errors.
  • rewind: Sets the file position to the beginning of the file.
  • ftell: Returns the current file position.
  • fseek: Sets the file position to a specific location.

Using file pointers in C allows efficient and flexible file operations, essential for managing persistent data.

Report an issue

Reporting: File Handling (topic)

Related Posts