Docsity

Data visualisation for btech sem1, Schemes and Mind Maps of Database Programming

Toggle sidebar
bg1
Problems to Read Data from Files in C
Simple notes with solved problems, sample input and output, and explanations
1. Introduction: Why Do We Read Data from Files?
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.
2. Important Definitions
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 .
Problems to Read Data from Files in C: Notes
Page 1 of 22
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16

Partial preview of the text

Download Data visualisation for btech sem1 and more Schemes and Mind Maps Database Programming in PDF only on Docsity!

Problems to Read Data from Files in C

Simple notes with solved problems, sample input and output, and explanations

1. Introduction: Why Do We Read Data from Files?

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.

2. Important Definitions

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.

3. The Five Steps to Read a File

Every file-reading program in C follows the same five steps.

  1. Declare a file pointer. Write FILE *fp;^ This creates the "bookmark" variable.
  2. Open the file. Write fp = fopen("numbers.txt", "r"); The first part is the file name. The second part, "r" , is the mode and means "open for reading".
  3. Check that the file opened. Write (^) if (fp == NULL). If the file does not exist or the name is wrong, fopen returns NULL. In that case, print an error message and stop the program. Skipping this check can make the program crash.
  4. Read the data. Use a reading function such as fscanf^ , fgetc^ or fgets^ inside a loop.
  5. Close the file. Write fclose(fp); This releases the file and keeps the system tidy.

3.1 Understanding the fopen line

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.

3.2 File opening modes

Mode Meaning What happens if the file does not exist "r" Open for reading only fopen fails and returns NULL

3.6 Preparing the input file

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.

4. Solved Problems with Step-by-Step Explanation

For every problem, you will find: the task, the idea, the program, a step-by-step explanation, and the output.

Problem 1: Display the contents of a file

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:

  1. #include ^ brings in the functions for input and output, including the file functions.
  2. FILE *fp; creates the file pointer. int ch; creates a variable to hold each character that we read.
  3. fopen("story.txt", "r") opens the file for reading and stores the result in fp.
  4. if (fp == NULL) checks whether opening failed. If yes, the program prints an error message and return 1; ends the program.
  5. In the while^ condition, fgetc(fp)^ reads one character and stores it in ch^. Then the program compares ch with EOF.
  6. If (^) ch is not (^) EOF , the loop body runs. (^) putchar(ch) prints that character on the screen.
  7. The loop repeats: the next character is read and printed. This continues until fgetc returns EOF.
  8. fclose(fp)^ closes the file, and return 0;^ ends the program normally.

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:

  1. The variables (^) count and (^) sum start at 0. (^) count will store how many numbers were read, and sum^ will store their total.
  2. The file is opened and checked, exactly as in Problem 1.
  3. fscanf(fp, "%d", &num) reads one integer from the file into num. It returns 1 if it succeeded. The loop continues as long as this value is 1.
  4. For the first number ( count == 0^ ), we set both max^ and min^ to that number, because there is nothing to compare it with yet.
  5. For every later number, we compare it with (^) max and (^) min. If it is bigger than (^) max , it becomes the new (^) max. If it is smaller than (^) min , it becomes the new (^) min.
  6. sum = sum + num adds the number to the total. count++ increases the counter by 1.
  7. When the file ends, fscanf no longer returns 1, so the loop stops. We close the file.
  8. If count^ is still 0, the file was empty, so we print a message. This also avoids dividing by zero.
  9. Otherwise, we print the results. (float)sum / count changes sum into a decimal number before dividing. Without this, C would do integer division and throw away the decimal part. (^) %.2f prints two digits after the decimal point.

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

Problem 3: Count the even and odd numbers in a file

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:

  1. Two counters, even and odd , start at 0.

#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:

  1. name is a character array that holds one student's name read from the file. topper is another character array that will hold the name of the best student so far.
  2. (^) maxMarks starts at -1, which is lower than any real mark, so the first student will always become the first topper. total and count start at 0.
  3. fscanf(fp, "%49s %d", name, &marks)^ reads one line. %49s^ reads a word of at most 49 characters (this prevents overflowing the 50-character array). %d then reads the marks. Notice that there is no &^ before name^ , because the name of an array already stands for its address.
  1. fscanf returns 2 when both the name and the marks are read. So the loop continues only while a complete line is read.
  2. Inside the loop, the marks are added to total and count goes up by 1.
  3. If these marks are higher than (^) maxMarks , this student is the new topper. We update maxMarks , and copy the name letter by letter into topper. The loop for (i = 0; name[i] != '\0'; i++) copies characters until the end-of-string character '\0'. Then topper[i] = '\0' marks the end of the copied string.
  4. After the file ends, we print the topper and the average, total / count.

(You can also copy the name with strcpy(topper, name);^ after adding #include .)

Dry run:

Output:

Topper : Ravi (91 marks) Average : 84.

Problem 5: Read numbers into an array and find the largest and second largest

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

  1. We go through the array. If a[i] is bigger than first , then the old first becomes the new second , and a[i] becomes the new first.
  2. Otherwise, if (^) a[i] is bigger than (^) second and different from (^) first , then (^) a[i] becomes the new second. The check a[i] != first stops a repeated maximum (like the second 45) from being taken as the second largest.
  3. At the end, if second is still INT_MIN , no second largest exists (for example, all numbers were equal).

Dry run:

Output: Largest = 45, Second largest = 30

Problem 6: Read numbers, reverse them, and write them into another file

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:

  1. We create two file pointers: in for the file we read from, and out for the file we write to.
  2. fopen("numbers.txt", "r")^ opens the input file for reading. We check for NULL^ as usual.
  3. The while loop reads every number into the array a , and n counts them, just like in Problem 5. Then we close in , because we no longer need it.
  4. (^) fopen("output.txt", "w") opens the output file in write mode. If the file does not exist, it is created. If it already exists, its old content is erased.
  5. The for loop starts at the last index n - 1 and goes down to 0. This visits the elements in reverse order.
  6. fprintf(out, "%d\n", a[i])^ works exactly like printf^ , but it writes into the file out instead of the screen. Each number goes on its own line.
  7. We close the output file with fclose(out). This makes sure all data is saved. Finally, a message is printed on the screen.

Result in output.txt :

printf("%d is not present in the file.", key); } return 0; }

Step-by-step explanation:

  1. The file is opened, and all numbers are loaded into the array (^) a. (^) n stores how many numbers were read. Then the file is closed. (This is the same method as Problem 5.)
  2. scanf("%d", &key)^ takes the number to search from the keyboard. Notice that we use scanf for the keyboard and fscanf for the file.
  3. found^ is a flag. It is 0 at the start, which means "not found yet".
  4. The for loop checks a[0] , a[1] , a[2] and so on. If a[i] == key , we print the position, set (^) found = 1 , and use (^) break to leave the loop at once.
  5. Array indexes start at 0, so the normal (human) position is i + 1. For key 9, the index is 2 and the position is 3.
  6. After the loop, if found is still 0, the key was never found, so we print that it is not present.

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.

Problem 8: Count how many times a word appears in a file

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:

  1. #include is needed for strcmp.
  2. word^ holds the word just read from the file. target^ holds the word typed by the user. count is the counter.
  3. scanf("%99s", target) reads the word to search for from the keyboard. %99s allows at most 99 characters, so the array does not overflow.
  4. (^) fscanf(fp, "%99s", word) reads one word from the file. The format (^) %s stops at a space, tab or new line, so each call gives the next word. It returns 1 while a word is available.
  5. strcmp(word, target) == 0 checks whether the two words are exactly the same. We cannot use ==^ to compare strings in C, because that would compare addresses, not letters.
  6. If the words match, count++ adds 1.
  7. When the file ends, we close it and print the count.

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.

  1. This repeats for every character until the source file ends.
  2. We close both files and print a success message.

Problem 10: Count the characters, words and lines in a file

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:

  1. chars , words and lines are counters that start at 0.
  2. inWord is a flag. It is 1 when we are currently inside a word, and 0 when we are outside a word (at a space, tab or new line).
  3. Each time (^) fgetc reads a character, (^) chars increases by 1 (spaces and new lines are counted too).
  4. If the character is '\n' (new line), lines increases by 1.
  5. If the character is a space, new line or tab, we are between words, so inWord = 0.
  6. Otherwise, the character is part of a word. If inWord was 0, a new word has just started , so we set inWord = 1 and increase words by 1. If inWord was already 1, we are in the middle of a word and nothing changes. This way, each word is counted only once, at its first letter.
  7. When (^) EOF is reached, the file is closed and the three counts are printed.

Note: If the last line does not end with a new-line character, it is not counted in lines.

5. Comparison of the Reading Methods

6. Common Mistakes to Avoid

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