ScholarQuill logoScholarQuillUniversity Notes
  • Notes
  • Past Papers
  • Blogs
  • Todo
Login
ScholarQuill logoScholarQuillUniversity Notes
Login
NotesPast PapersBlogsTodo
More
SubjectsDiscussionCGPA CalculatorGPA CalculatorStudent PortalCourse Outline
About
About usPrivacy PolicyReportContact
Notes
Past Papers
Blogs
Todo
Analytics
    Current Subject
    🧩
    Programming Fundamentals
    CSI-311
    Progress0 / 17 topics
    Topics
    1. Overview of Computers and Programming2. Overview of Languages (e.g., C Language)3. Basics of Structured and Modular Programming4. Basic Algorithms and Problem Solving5. Development of Basic Algorithms6. Analyzing Problems7. Designing Solutions8. Testing Designed Solutions9. Fundamental Programming Constructs10. Translation of Algorithms to Programs11. Data Types12. Control Structures13. Functions14. Arrays15. Records16. Files17. Testing Programs
    CSI-311›Files
    Programming FundamentalsTopic 16 of 17

    Files

    7 minread
    1,191words
    Intermediatelevel

    Files in C Language

    In C programming, files are used to store data permanently, either for input or output. C provides a set of functions for working with files, allowing you to read from and write to them. These files can be of two types:

    • Text files: Contain human-readable data (such as letters, numbers, and symbols).
    • Binary files: Contain data in a binary format (such as images, audio files, or data structures in their raw binary form).

    Working with files is a crucial aspect of C programming, particularly when you need to store large amounts of data or retrieve data for later use. C offers functions that allow you to open, read, write, and close files.


    1. File Handling Functions in C

    To work with files in C, you use the standard library provided by C, particularly <stdio.h>, which includes functions for opening, reading, writing, and closing files.

    a) Opening a File: fopen()

    The fopen() function is used to open a file. It takes two parameters:

    1. The name of the file (including its path).
    2. The mode in which the file should be opened.
    • Syntax:

      FILE *fopen(const char *filename, const char *mode);
      
    • Modes:

      • "r": Opens the file for reading. If the file does not exist, the operation fails.
      • "w": Opens the file for writing. If the file exists, it is overwritten. If it does not exist, a new file is created.
      • "a": Opens the file for appending. Data is added at the end of the file.
      • "r+": Opens the file for both reading and writing. The file must exist.
      • "w+": Opens the file for both reading and writing. The file is created or overwritten.
      • "a+": Opens the file for both reading and appending.
    • Example:

      FILE *file = fopen("example.txt", "w");  // Open "example.txt" for writing
      if (file == NULL) {
          printf("Error opening file.\n");
          return 1;
      }
      

    If fopen() fails to open the file (for example, due to insufficient permissions or an incorrect path), it returns NULL.

    b) Closing a File: fclose()

    Once you're done working with a file, you should always close it using fclose(). This releases any resources allocated for the file.

    • Syntax:

      int fclose(FILE *stream);
      
    • Example:

      fclose(file);  // Close the file after use
      

    2. Reading from a File

    There are several functions to read from a file, depending on the type of data you want to read.

    a) fgetc() – Read a Single Character

    • Syntax:

      int fgetc(FILE *stream);
      
    • Example:

      char c;
      FILE *file = fopen("example.txt", "r");
      if (file == NULL) {
          printf("Error opening file.\n");
          return 1;
      }
      
      c = fgetc(file);  // Read a single character
      printf("%c\n", c);  // Print the character
      fclose(file);
      

    fgetc() returns the next character from the file. If it reaches the end of the file, it returns EOF (end-of-file).

    b) fgets() – Read a String (Line)

    • Syntax:
      char *fgets(char *str, int n, FILE *stream);
      

    fgets() reads a line from the file into a string. The second parameter (n) specifies the maximum number of characters to read.

    • Example:
      char buffer[100];
      FILE *file = fopen("example.txt", "r");
      if (file == NULL) {
          printf("Error opening file.\n");
          return 1;
      }
      
      fgets(buffer, sizeof(buffer), file);  // Read a line into buffer
      printf("Line: %s", buffer);  // Print the line
      fclose(file);
      

    c) fread() – Read Binary Data

    fread() is used to read binary data from a file.

    • Syntax:

      size_t fread(void *ptr, size_t size, size_t count, FILE *stream);
      
    • Example:

      FILE *file = fopen("binary.dat", "rb");
      if (file == NULL) {
          printf("Error opening file.\n");
          return 1;
      }
      
      int arr[5];
      fread(arr, sizeof(int), 5, file);  // Read 5 integers from the file
      fclose(file);
      

    3. Writing to a File

    Just like reading, there are different functions for writing to a file based on the type of data you wish to write.

    a) fputc() – Write a Single Character

    • Syntax:

      int fputc(int char, FILE *stream);
      
    • Example:

      FILE *file = fopen("example.txt", "w");
      if (file == NULL) {
          printf("Error opening file.\n");
          return 1;
      }
      
      fputc('A', file);  // Write a single character to the file
      fclose(file);
      

    b) fputs() – Write a String

    • Syntax:

      int fputs(const char *str, FILE *stream);
      
    • Example:

      FILE *file = fopen("example.txt", "w");
      if (file == NULL) {
          printf("Error opening file.\n");
          return 1;
      }
      
      fputs("Hello, World!", file);  // Write a string to the file
      fclose(file);
      

    c) fwrite() – Write Binary Data

    fwrite() is used to write binary data to a file.

    • Syntax:

      size_t fwrite(const void *ptr, size_t size, size_t count, FILE *stream);
      
    • Example:

      FILE *file = fopen("binary.dat", "wb");
      if (file == NULL) {
          printf("Error opening file.\n");
          return 1;
      }
      
      int arr[5] = {1, 2, 3, 4, 5};
      fwrite(arr, sizeof(int), 5, file);  // Write 5 integers to the file
      fclose(file);
      

    4. File Positioning Functions

    You can move the file pointer to a specific position in a file using these functions.

    a) fseek() – Move the File Pointer

    • Syntax:
      int fseek(FILE *stream, long offset, int whence);
      

    fseek() moves the file pointer to a specific location. The whence parameter can be:

    • SEEK_SET: Set the position to offset from the beginning.

    • SEEK_CUR: Set the position to offset from the current position.

    • SEEK_END: Set the position to offset from the end of the file.

    • Example:

      FILE *file = fopen("example.txt", "r");
      if (file == NULL) {
          printf("Error opening file.\n");
          return 1;
      }
      
      fseek(file, 10, SEEK_SET);  // Move the pointer 10 bytes from the beginning
      fclose(file);
      

    b) ftell() – Get the Current Position

    ftell() returns the current position of the file pointer.

    • Syntax:

      long ftell(FILE *stream);
      
    • Example:

      FILE *file = fopen("example.txt", "r");
      if (file == NULL) {
          printf("Error opening file.\n");
          return 1;
      }
      
      fseek(file, 10, SEEK_SET);  // Move the pointer
      long pos = ftell(file);     // Get the current position
      printf("Current position: %ld\n", pos);
      fclose(file);
      

    5. Error Handling

    C provides a set of functions for detecting file errors.

    a) feof() – Check for End of File

    feof() checks whether the end of the file has been reached.

    • Syntax:

      int feof(FILE *stream);
      
    • Example:

      FILE *file = fopen("example.txt", "r");
      char ch;
      while ((ch = fgetc(file)) != EOF) {
          putchar(ch);  // Print characters until end of file
      }
      fclose(file);
      

    b) ferror() – Check for File Errors

    ferror() checks for errors during reading or writing operations.

    • Syntax:

      int ferror(FILE *stream);
      
    • **Example

    Previous topic 15
    Records
    Next topic 17
    Testing Programs

    Past Papers

    Open this section to load past papers

    Click on Show Past Papers to see past papers.
    On This Page
      Reading Stats
      Est. reading time7 min
      Word count1,191
      Code examples0
      DifficultyIntermediate