Unlocking the Power of File Handling in C Programming
The Problem Statement
Imagine you have a file named program.txt
containing a text message in the current directory. Your task is to create a program that reads the first line from this file and saves its content to a string until a newline character (\n
) is encountered.
The Solution
To tackle this challenge, you’ll need to possess knowledge of C file handling and string programming concepts. The program will open the program.txt
file and read its content character by character, storing it in a string until a newline character is detected.
The Code
#include <stdio.h>
#include <stdlib.h>
int main() {
FILE *fp;
char c, str[100];
fp = fopen("program.txt", "r");
if (fp == NULL) {
printf("Error: File not found\n");
exit(1);
}
int i = 0;
while ((c = fgetc(fp))!= '\n' && c!= EOF) {
str[i++] = c;
}
str[i] = '\0';
printf("First line: %s\n", str);
fclose(fp);
return 0;
}
How it Works
Let’s break down the code step by step:
- We open the
program.txt
file in read mode (“r
“). - If the file is not found, an error message is printed, and the program terminates.
- We create a character array
str
to store the first line of the file. - The
while
loop reads characters from the file until a newline character or the end of the file is reached, storing each character in thestr
array. - Finally, we print the first line and close the file.
The Output
If the program.txt
file contains the following text:
This is the first line. This is the second line.
The program’s output will be:
First line: This is the first line.
On the other hand, if the file is not found, the program will print:
Error: File not found