C Files

1. What is File Handling in C?

  • File 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

#include <stdio.h>

int main() {
FILE *fp = fopen(“example.txt”, “r”);
if (fp == NULL) {
printf(“File not found!\n”);
return 1;
}

char ch;
while ((ch = fgetc(fp)) != EOF) {
printf(“%c”, ch);
}

fclose(fp);
return 0;
}


5. Writing to a File

  • fputc() → write a single character

  • fputs() → write a string

  • fprintf() → formatted output

Example: Writing to a file

#include <stdio.h>

int main() {
FILE *fp = fopen(“output.txt”, “w”);
if (fp == NULL) {
printf(“Unable to create file!\n”);
return 1;
}

fputs(“Hello, C File Handling!\n”, fp);
fprintf(fp, “Number: %d\n”, 100);

fclose(fp);
return 0;
}


6. Reading & Writing (r+) Example

#include <stdio.h>

int main() {
FILE *fp = fopen(“data.txt”, “r+”);
if (fp == NULL) {
printf(“File not found!\n”);
return 1;
}

// Write at the beginning
fprintf(fp, “Updated Line\n”);

// Move pointer to beginning
fseek(fp, 0, SEEK_SET);

char line[100];
while (fgets(line, sizeof(line), fp) != NULL) {
printf(“%s”, line);
}

fclose(fp);
return 0;
}


7. Checking File Open

if (fp == NULL) {
printf("Error opening file!\n");
return 1;
}

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.

CodeCapsule

Sanjit Sinha — Web Developer | PHP • Laravel • CodeIgniter • MySQL • Bootstrap Founder, CodeCapsule — Student projects & practical coding guides. Email: info@codecapsule.in • Website: CodeCapsule.in

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *