ScholarQuill logoScholarQuillUniversity Notes
My Semester
Explore Notes
Past Papers12 New
Video CoursesNew
Search
Settings
Study Tools
GPA/CGPA Calculator
Schedule & To-Do
Student Portal
Contact
Contact
ScholarQuill logo
My Semester
Explore Notes
Past Papers12 New
Video CoursesNew
Search
Settings
GPA/CGPA Calculator
Schedule & To-Do
Student Portal
Contact
ScholarQuill logoScholarQuillUniversity Notes
Study PortalCSI-311Files
Ctrl + K
Login
Explore
Search
Semester
Papers
CGPA
    CSI-311

    Programming Fundamentals

    Progress0 / 17 done
    Topics17
    1Overview of Computers and Programming2Overview of Languages (e.g., C Language)3Basics of Structured and Modular Programming4Basic Algorithms and Problem Solving5Development of Basic Algorithms6Analyzing Problems7Designing Solutions8Testing Designed Solutions9Fundamental Programming Constructs10Translation of Algorithms to Programs11Data Types12Control Structures13Functions14Arrays15Records16Files17Testing Programs
    7 min read
    Topic 16 of 17
    Topic Study Note Illustration
    16

    Files

    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...

    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 view and download past papers

    Click on Show Past Papers to load available exam papers.

    Reading Progress
    0%
    7mremaining
    1.2kwords
    Intermediatelevel
    On This Page

    No headings found

    Study Toolkit

    Subject Portal

    Programming Fundamentals