














Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!















Simple notes with solved problems, sample input and output, and explanations
When we type data on the keyboard, the computer keeps it only while the program is running. When the program ends, the data is gone. If we need the same data again, we must type it again.
A file solves this problem. A file keeps data safely on the disk, even after the program ends or the computer is switched off. A program can open the file and read the data whenever it needs.
Real-life example: A teacher stores the marks of 100 students in a file called (^) marks.txt. Instead of typing 100 numbers every time, the teacher runs a C program. The program reads the file by itself and finds the average, the highest mark, and so on, in a moment.
In this unit, "reading data from files" means: a C program opens a file, takes the data out of it, uses that data to solve a problem, and then closes the file.
Learn these simple definitions first. They make every program easier to understand.
File: a named place on the disk where data is stored permanently. Example: numbers.txt. Text file: a file that stores data as readable characters, like letters, digits and spaces. You can open it in Notepad and read it. In this unit, we use only text files. Binary file: a file that stores data in the computer's own format (0s and 1s). It cannot be read in Notepad. We do not use it in these notes. File pointer: a special variable that connects our program to a file. It is declared as FILE *fp; (^). Think of it as a bookmark : it remembers which file is open and how far we have read. FILE : a data type defined in the header file stdio.h. It holds all the information about an open file. fopen() : the function that opens a file. It gives back a file pointer. fclose() :^ the function that^ closes^ a file after we finish using it. NULL : a special value that means "nothing". If fopen fails, it returns NULL.
Reading position: the place in the file from where the next read will start. After each read, this position moves forward automatically. EOF (End Of File): a special signal that tells the program there is no more data to read. Return value: the answer that a function gives back. File-reading functions return a value that tells us whether the reading worked or the file has ended. We use it to stop our loops. Format specifier: a code that tells (^) fscanf what type of data to read. (^) %d is for an integer, %f for a decimal number, %s for a word, and %c for a single character.
Every file-reading program in C follows the same five steps.
fp = fopen("numbers.txt", "r");
"numbers.txt" is the name of the file. The file must be in the same folder as the program, or you must write the full path. "r" is the mode. It means^ read only. The program can read the file but cannot change it. fopen returns the file pointer, which we store in fp. From now on, we use fp to talk to the file.
Mode Meaning What happens if the file does not exist "r" Open for reading only fopen fails and returns NULL
Open Notepad, type the data, and save the file with a (^) .txt name in the same folder as your C program. For example, numbers.txt may contain:
10 25 7 42 18
Numbers can be separated by spaces or placed on separate lines. fscanf skips both.
For every problem, you will find: the task, the idea, the program, a step-by-step explanation, and the output.
Task: Read a text file and show its content on the screen.
Idea: Read the file one character at a time and print each character, until the end of the file comes.
Sample input ( story.txt ): Hello C
Call Number read Return value Reading position now 1st 10 1 after 10 2nd 25 1 after 25 3rd 7 1 after 7 4th nothing left not 1 (end of file) at the end, so the loop stops
#include
int main() { FILE *fp; int ch;
fp = fopen("story.txt", "r"); if (fp == NULL) { printf("Error: could not open the file.\n"); return 1; }
while ((ch = fgetc(fp)) != EOF) { putchar(ch); }
fclose(fp); return 0; }
Step-by-step explanation:
Why is (^) ch an (^) int and not a (^) char? (^) EOF is an integer value (usually -1). A (^) char variable may not store it correctly, so we use int^.
Output: Hello C
printf("Minimum = %d\n", min); } return 0; }
Step-by-step explanation:
Dry run:
Output:
Number read count sum max min 10 1 10 10 10 25 2 35 25 10 7 3 42 25 7 42 4 84 42 7 18 5 102 42 7
Count = 5 Sum = 102 Average = 20. Maximum = 42 Minimum = 7
Task: Read integers from a file and count how many are even and how many are odd.
Definition: An even number is divisible by 2 with no remainder (4, 10, 22). An odd number leaves a remainder of 1 when divided by 2 (7, 15, 9).
Idea: For each number, find the remainder after dividing by 2, using the %^ operator. Remainder 0 means even; otherwise odd.
Sample input ( numbers.txt ): 4 7 10 15 22 9
#include
int main() { FILE *fp; int num, even = 0, odd = 0;
fp = fopen("numbers.txt", "r"); if (fp == NULL) { printf("Error: could not open the file.\n"); return 1; }
while (fscanf(fp, "%d", &num) == 1) { if (num % 2 == 0) { even++; } else { odd++; } } fclose(fp);
printf("Even numbers = %d\nOdd numbers = %d\n", even, odd); return 0; }
Step-by-step explanation:
#include
int main() { FILE *fp; char name[50], topper[50] = ""; int marks, maxMarks = -1, total = 0, count = 0, i;
fp = fopen("students.txt", "r"); if (fp == NULL) { printf("Error: could not open the file.\n"); return 1; }
while (fscanf(fp, "%49s %d", name, &marks) == 2) { total = total + marks; count++; if (marks > maxMarks) { maxMarks = marks; for (i = 0; name[i] != '\0'; i++) { topper[i] = name[i]; } topper[i] = '\0'; } } fclose(fp);
if (count == 0) { printf("No data found."); } else { printf("Topper : %s (%d marks)\n", topper, maxMarks); printf("Average : %.2f\n", (float)total / count); } return 0; }
Step-by-step explanation:
(You can also copy the name with strcpy(topper, name);^ after adding #include .)
Dry run:
Output:
Topper : Ravi (91 marks) Average : 84.
Task: Read the numbers from a file into an array. Then find the largest and the second largest numbers.
Definition: The second largest number is the biggest number that is smaller than the largest. If the largest number appears twice, the second largest is still a different, smaller value.
Sample input ( numbers.txt ): 10 45 20 45 30
#include #include
int main() { FILE *fp; int a[100], n = 0, i; int first = INT_MIN, second = INT_MIN;
Line read total count maxMarks topper Asha 78 78 1 78 Asha Ravi 91 169 2 91 Ravi Meena 85 254 3 91 Ravi
Dry run:
Output: Largest = 45, Second largest = 30
Task: Read the numbers from (^) numbers.txt and save them in reverse order in output.txt.
Idea: First read all numbers into an array. Then open a second file for writing and write the array elements from the last one to the first one.
Sample input ( numbers.txt^ ): 1 2 3 4 5
#include
int main() { FILE *in, *out; int a[100], n = 0, i;
in = fopen("numbers.txt", "r"); if (in == NULL) { printf("Error: could not open the input file.\n"); return 1; }
Element first second What happened 10 10 MIN 10 is bigger than first 45 45 10 45 is bigger; the old first moves to second 20 45 20 20 is bigger than second 45 45 20 Equal to first, so ignored 30 45 30 30 is bigger than second
while (n < 100 && fscanf(in, "%d", &a[n]) == 1) { n++; } fclose(in);
out = fopen("output.txt", "w"); if (out == NULL) { printf("Error: could not create the output file.\n"); return 1; }
for (i = n - 1; i >= 0; i--) { fprintf(out, "%d\n", a[i]); } fclose(out);
printf("%d numbers written in reverse order to output.txt", n); return 0; }
Step-by-step explanation:
Result in output.txt :
printf("%d is not present in the file.", key); } return 0; }
Step-by-step explanation:
Dry run (key = 9): (^) a[0] = 7 no, (^) a[1] = 3 no, (^) a[2] = 9 yes, so the search stops after 3 comparisons.
Output: 9 found at position 3 (index 2)
If the numbers in the file are already sorted, binary search can be used instead of linear search for faster results.
Task: Read a text file word by word and count how many times a word given by the user appears.
Definition: A string in C is an array of characters that ends with the special character '\0'. The function strcmp(s1, s2) compares two strings. It returns 0 when they are exactly equal.
Sample input ( story.txt ): the cat and the dog and the bird. Word to count: the.
#include #include
int main() { FILE *fp; char word[100], target[100]; int count = 0;
fp = fopen("story.txt", "r"); if (fp == NULL) { printf("Error: could not open the file.\n"); return 1; }
printf("Enter the word to count: "); scanf("%99s", target);
while (fscanf(fp, "%99s", word) == 1) { if (strcmp(word, target) == 0) { count++; } } fclose(fp);
printf("The word "%s" appears %d time(s).", target, count); return 0; }
Step-by-step explanation:
Dry run: The words are the, cat, and, the, dog, and, the, bird. The target is the , and it matches 3 times.
Output: The word "the" appears 3 time(s).
Limitation: This simple method sees the,^ (with a comma) or The^ (with a capital letter) as different from the.
Task: Find how many characters, words and lines a text file contains.
Idea: Read the file one character at a time. Count every character. Count every new-line character as one line. Count a word whenever a new word begins.
Sample input ( story.txt ):
I like C Files are fun
#include
int main() { FILE *fp; int ch, chars = 0, words = 0, lines = 0, inWord = 0;
fp = fopen("story.txt", "r"); if (fp == NULL) { printf("Error: could not open the file.\n"); return 1; }
while ((ch = fgetc(fp)) != EOF) { chars++; if (ch == '\n') { lines++; } if (ch == ' ' || ch == '\n' || ch == '\t') { inWord = 0; } else if (inWord == 0) { inWord = 1; words++; } } fclose(fp);
printf("Characters = %d\nWords = %d\nLines = %d\n", chars, words, lines); return 0; }
Step-by-step explanation:
Note: If the last line does not end with a new-line character, it is not counted in lines.
Not checking (^) fopen. If the file is missing, (^) fp is (^) NULL and the program may crash. Always test fp == NULL. Wrong file name or folder. The file must be in the same folder as the program, or the full path must be given. Windows may hide the extension, so a file that looks like numbers.txt may really be numbers.txt.txt. Forgetting fclose(fp)^. Always close the file when you finish. Using "w" by mistake. This erases the old content. To read a file, use "r".
Method Reads The loop stops when
Use it for
fscanf(fp, "%d", &x) One number^ The result is not 1^ Lists of numbers fscanf(fp, "%s", word)
One word The result is not 1 Word-based problems
fgetc(fp) One character
The result is EOF Counting, copying, displaying fgets(line, size, fp)
One line The result is NULL^ Line-by-line processing