DEV Community

Rita Kairu
Rita Kairu

Posted on • Updated on

A Quick Guide to File Manipulation (I/O) in C

File operations in C are essential for reading from and writing to files on the system. They involve several functions and concepts that enable you to manipulate files efficiently. Here's a brief overview of file operations in C:

1. File Pointers

  • File pointers are used to handle files in C programs.
  • They are of type FILE and are declared using the FILE structure.
  • Example: FILE *fp;

2. Opening Files

  • fopen() function is used to open files.
  • Syntax: FILE *fopen(const char *filename, const char *mode);
  • Modes:
    • "r": Read mode
    • "w": Write mode (creates a new file or overwrites existing content)
    • "a": Append mode (appends data at the end of the file)
    • "r+": Read/write mode (file must exist)
    • "w+": Read/write mode (creates a new file or overwrites existing content)
    • "a+": Read/append mode (file is created if it does not exist)
  • Returns a pointer to the file.

3. Closing Files

  • fclose() function is used to close files.
  • Syntax: int fclose(FILE *fp);
  • It flushes any buffered data and releases the associated file descriptor.

4. Reading from Files

  • fgetc() reads a character from the file.
  • fgets() reads a line from the file.
  • fread() reads blocks of data from the file.
  • Example:
  char buffer[255];
  fgets(buffer, 255, fp); // Reads a line from the file into buffer
Enter fullscreen mode Exit fullscreen mode

5. Writing to Files

  • fputc() writes a character to the file.
  • fputs() writes a string to the file.
  • fwrite() writes blocks of data to the file.
  • Example:
  fprintf(fp, "This is a formatted string: %s\n", str);
Enter fullscreen mode Exit fullscreen mode

6. Error Handling

  • Always check if file operations succeed.
  • Use feof() and ferror() to handle end-of-file and error conditions respectively.

7. File Positioning

  • fseek() and rewind() are used to move the file pointer.
  • ftell() returns the current position of the file pointer.

8. Binary vs. Text Mode

  • Files can be opened in binary mode by adding 'b' to the mode string.
  • Binary mode prevents newline translation and treats file contents as binary data.

9. Error Handling

  • Always check the return values of file operations.
  • Handle errors gracefully to avoid unexpected behavior.

Sample Code:

#include <stdio.h>

int main() {
    FILE *fp;
    char buffer[255];

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

    // Write to file
    fprintf(fp, "This is just an example!\n");

    // Read from file
    rewind(fp);
    fgets(buffer, 255, fp);
    printf("Content: %s", buffer);

    // Close file
    fclose(fp);

    return 0;
}
Enter fullscreen mode Exit fullscreen mode

Important Points:

  • Always close files after using them to prevent resource leaks.
  • Handle file operations errors appropriately.
  • Use binary mode when dealing with binary data.

Understanding file operations is crucial for many applications, especially those involving data storage and manipulation. Mastering file operations in C allows you to work with files seamlessly.

Top comments (2)

Collapse
 
pauljlucas profile image
Paul J. Lucas

Without an example for each function, this really isn't comprehensive.

Collapse
 
thecodingcivilengineer profile image
Rita Kairu

Thank you Paul for your honest feedback🌟.