C Files

C Tutorial

1. What is File Handling in C?

  • C Files handling allows a program to store data permanently in a file on disk.

  • Types of files in C:

    1. Text files → store readable characters (.txt)

    2. Binary files → store data in binary format (.bin)

  • File handling in C uses the FILE structure provided in stdio.h.


2. Opening a File

FILE *fopen(const char *filename, const char *mode);
  • filename → name of the file

  • mode → how the file is to be opened

Mode Description
"r" Read (file must exist)
"w" Write (creates file or overwrites)
"a" Append (write at end, creates file)
"r+" Read & write (file must exist)
"w+" Read & write (creates/overwrites)
"a+" Read & append (creates file)

3. Closing a File

int fclose(FILE *fp);
  • Always close a file after operations to save data and free resources.


4. Reading from a File

  • fgetc() → read a single character

  • fgets() → read a line/string

  • fscanf() → formatted input

Example: Reading a file character by character


 


5. Writing to a File

  • fputc() → write a single character

  • fputs() → write a string

  • fprintf() → formatted output

Example: Writing to a file


 


6. Reading & Writing (r+) Example


 


7. Checking File Open

Always check if fopen was successful before performing operations.


8. Key Points About C File Handling

  1. Use FILE * for file operations.

  2. Always open a file with proper mode (r, w, a, etc.).

  3. Always close files using fclose() after operations.

  4. Use fgetc(), fgets(), fputc(), fputs(), fprintf(), fscanf() for reading/writing.

  5. Use fseek(), ftell(), and rewind() for file pointer control.

  6. File handling allows persistent storage beyond program execution.

You may also like...