Files

Abstract File and Data Storage in Programming

  • Understanding the abstraction provided by files for data storage.

    • Files allow saving data persistently, which can be accessed after program termination and restart.

    • Data can be transferred between different applications.

Types of Files

  • File Formats: Data can be stored in two main types of formats:

    • Text Files:

    • Typically contain ASCII characters.

    • Visually readable with letters and symbols.

    • Commonly used to store records, emails, and documents.

    • Examples: .txt, .csv, .html files.

    • Binary Files:

    • Used for non-textual data such as images and audio.

    • Not visually readable in standard text editors.

    • Examples: .jpg, .mp3, .bin files.

Accessing Files

  • Modes of Access: Files can be accessed in two different ways:

    • Serial Access (Sequential Access):

    • Begin at the start and read sequentially through the entire file.

    • Suitable for files where entire content is required, e.g., reading a text file line-by-line.

    • Random Access:

    • Allow jumping to any part of the file without sequential reading.

    • Example usage: modifying or retrieving data near the end of a large file without reading the entire file.

File Handling in Programming

  • Open and Close Files:

    • Use fopen to open a file. This function requires two parameters: file name and mode.

    • File Name: The name of the file to be opened.

    • Mode: Indicates how the file will be used (e.g., read, write, append).

    • Always close the file after operations with fclose. Failing to do so can lead to unflushed data.

  • File Pointer:

    • A file pointer, assigned during file opening, navigates through the contents of the file.

    • In serial access, the pointer moves line by line; in random access, it jumps around as needed.

  • Example:

  FILE *fp;
  fp = fopen("input.txt", "r"); // Opening the file for reading
  if (fp != NULL) {
      // Work with the file
      fclose(fp); // Close the file when done
  }

Managing File Access Modes in C

  • File Modes:

    • Common modes include:

    • r : read mode

    • w : write mode (creates a new file or overwrites existing)

    • a : append mode (adds to existing content)

  • Handling Errors:

    • After calling fopen, check if the file pointer is NULL to ensure the file opened successfully.

  • File Status Checks:

    • If a file pointer is NULL, dereferencing it can cause program crashes.

Example of Copying Files

  • Basic File Copy Operation:

    • Steps:

    • Open source file for reading.

    • Open destination file for writing.

    • Read content from source and write to destination.

    • Close both files.

  • Code Snippet:

  FILE *infile, *outfile;
  infile = fopen("input.txt", "r");
  outfile = fopen("output.txt", "w");
  if (infile != NULL && outfile != NULL) {
      char c;
      while ((c = fgetc(infile)) != EOF) {
          fputc(c, outfile);
      }
      fclose(infile);
      fclose(outfile);
  }
  • Error Handling During File Opening:

    • Implement prompts or flags to inform users if files cannot be opened due to permissions, filepath errors, or locking issues.

Reading and Searching in Files

  • Functions to read lines and perform searches:

    • Using fgets for reading lines:

   char line[1200];
   while (fgets(line, sizeof(line), fp) != NULL) {
       // Process the line
   }
  • Pattern searching in strings can be achieved with functions like strstr.

    • Sample Search Algorithm:

  • Open a file and use fgets to iterate through each line, searching for a specific term.

Dealing with Binary Files

  • Binary Files:

    • Typically contain non-character data (e.g., images).

    • Requires different operations compared to text files (using fread, fwrite).

    • Use appropriate structures to represent data.

  • Using fseek for Random Access in Binary Files:

    • fseek(fp, offset, whence) allows moving the file pointer to specified locations.

    • ftell(fp) can be used to obtain the current position of the file pointer.

  • Example of Writing to Binary File:

  FILE *bfile = fopen("image.bin", "wb");
  if (bfile) {
      // write data
      fclose(bfile);
  }

Summary of Key Commands

  • File Operations:

    • fopen(): Opens a file.

    • fclose(): Closes a file.

    • fgetc(), fgets(): Read characters or lines from a file.

    • fputc(): Write characters to a file.

    • fread(), fwrite(): Read and write binary data.

    • fseek(), ftell(): Navigate and obtain positions in files.

  • Each operation must check for errors to avoid program crashes and data loss.

Conclusion

  • This comprehensive understanding of file handling, types, access modes, and operations in C lays the groundwork for developing robust software that effectively manages data across sessions and applications.