C Read Files

1. Opening a File for Reading

Use fopen() with read mode:


 

Mode Description
"r" Read (file must exist)
"r+" Read & write (file must exist)
"a+" Read & append (creates file if not exist)

2. Reading Functions in C

Function Description
fgetc(fp) Reads a single character from the file
fgets(buffer, size, fp) Reads a line/string from the file
fscanf(fp, "format", &variables) Reads formatted input

3. Example 1: Reading File Character by Character

#include <stdio.h>

int main() {
FILE *fp = fopen("output.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;
}

  • fgetc() reads one character at a time.

  • Loop continues until EOF (End of File) is reached.


4. Example 2: Reading File Line by Line Using fgets

#include <stdio.h>

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

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

fclose(fp);
return 0;
}

  • fgets() reads up to size-1 characters or until newline.

  • Includes the newline character at the end.


5. Example 3: Reading Formatted Data Using fscanf

#include <stdio.h>

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

int age;
double salary;

fscanf(fp, "Age: %d\n", &age);
fscanf(fp, "Salary: %lf\n", &salary);

printf("Age = %d\n", age);
printf("Salary = %.2lf\n", salary);

fclose(fp);
return 0;
}

Output (if data.txt has Age: 25 and Salary: 45000.50):

Age = 25
Salary = 45000.50

6. Checking File Open

FILE *fp = fopen("file.txt", "r");
if (fp == NULL) {
printf("Unable to open file!\n");
return 1;
}
  • Always check if the file exists before reading.


7. Key Points About Reading Files

  1. Use read mode (r) to open a file.

  2. Always check if fopen was successful.

  3. Functions for reading:

    • fgetc() → single character

    • fgets() → line/string

    • fscanf() → formatted input

  4. Loop until EOF for complete reading.

  5. Always close files with fclose() after reading.

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 *