C Programming

How to Read Input from a File in C

The information will be lost once a program is ended. When we save the data in a file, it will be retained although the program crashes. If we a lot of data to insert, this would require more time to do. But, if we have a file that includes all of the content, we would quickly retrieve it by using some C functions. We will directly transfer the file from one device to the other without modifications.

There are two types of files: text and binary. Text files are those with the extension .txt. These files are simple to make. When we access these files, we’ll get a clear text for all the information. The data can be simply modified or deleted. The extension .bin denotes a binary file. Rather than retaining information in clear text, they do it in binary numbers (0s and 1s).

Let’s discuss in detail the various approaches on how to read the content of a file.

Using fseek() function to read input from the file

If we have a large number of entries in a file and we want to retrieve them one by one at a particular position, then we must iterate through every item before this. It would consume a significant amount of memory and processing time. Through the fseek() function, we can obtain the needed information more efficiently.

#include <stdio.h>

#include <stdlib.h>

struct thrNumber
{
   int num1, num2, num3;
};
int main()
{
   int n;
   struct thrNumber number;
   FILE *fptr;
   if ((fptr = fopen("file_1.txt", "r")) == NULL){
       printf("File cannot open");
      exit(1);
   }
   fseek(fptr, -sizeof(struct thrNumber), SEEK_END);
   for(n = 1; n < 5; ++n)
   {
      fread(&number, sizeof(struct thrNumber), 1, fptr);
      printf("n1: %d\tn2: %d\tn3: %d\n", number.num1, number.num2, number.num3);
      fseek(fptr, -2*sizeof(struct thrNumber), SEEK_CUR);
   }
   fclose(fptr);  
   return 0;
}

Here we are going to start the program by integrating required header files #include <stdio.h> and #include <stdlib.h>. Now we create a function and then three different variables are initialized. These variables have an integer data type. After this, we declare the main() function and start coding in the body of the main() function.

In addition to this, we construct a file pointer. “If” statement is then applied. Here, we set the file pointer equal to the fopen() function. The fopen () function is used to open the specified file. With the help of the if statement, we check if the given path of the file is equal to ‘NULL’ printf statement prints the text ‘File cannot open’. Otherwise, the program exits.

Further fseek() method is utilized. It holds three parameters. The first argument contains the file pointer. The second argument shows the location of the given file. Similarly, the last argument indicates the point from where the deviation begins. In addition to this, we apply for a loop. We declare the variable and set the condition for the number and then lastly, we do an increment in the value of a number.

To get the text from the specified file, we employ the fread() function. Now we have to print the result so the printf() function is used. Once again, we apply the fseek() function. In the end to close the given file, we used the fclose() function.

Using fgetc() function to read input from a file

The fgetc() function retrieves the characters referred to by the function indicator. It provides the word received by the stream and adjusts the reading point towards the next word after every valid read. But if no data is present to read, this method computes a variable EOF (-1).

#include <stdio.h>

#include <stdlib.h>

#include <string.h>

int main()
{
    FILE* fptr;
    char chr;
    fptr = fopen("data.txt", "r");
    if (NULL == fptr) {
        printf("file can not open \n");
    }
    printf("Data of the file is \n Name : Amna \n Age : 24 \n Name : Sara \n Age : 16 \n Name :Aneela \n Age : 30 \n");
    do {
        chr = fgetc(fptr);
        printf("%c", chr);
    } while (chr != EOF);
    fclose(fptr);
    return 0;
}

First of all, we include three header files. Standard Library is the identifier of the header file <stdlib.h>. It contains data about storage availability and free methods. Standard Input-Output is the identifier of the header file <stdio.h>. It contains data about input/output methods. The header file <string> includes macro declarations, variables, and definitions of methods and classes that are used not just for text processing but also for different storage handling functions.

In the next step, we initialize the main() function. Here, a pointer of a specified file is constructed and we declare a variable having a character data type. Next, we utilize the fopen() function. This method contains two arguments: the first parameter shows the file name and the second parameter shows the mode of the file. Here, the fopen() method opens the defined file in the reading mode. We have been using the if statement to check whether the pointer of the file is equal to ‘NULL’ or not. If the file pointer equals ‘NULL,’ then the specified program terminates. Otherwise, we employ the printf() function to print the contents of the file.

In addition to this, by the use of a do-while loop, we go through each character one by one. Here, we declare the fgetc() function to retrieve the data from the defined file. Now, we apply the while loop to examine if the given character would not be at the end of the line; if it would be, quit reading. The fclose() method is used and this brings the file to a close.

While using the fgetc() function, the above-mentioned code reads the entire data of the file, a single character at a time. A Do-While loop would be used to retrieve characters unless they come to the end of the file. It produces the EOF (-1) char whenever it attains the conclusion.

Conclusion

In this article, we have gone through different ways that are used to read the data from the file. Here we have applied fgetc(), fread(), and fseek() methods for getting content with the help of particular examples. These all are pre-defined functions of the C language. To read every single word of a file, we have used the fgetc() method. Similarly to extract configured data to a file, we have used the fseek() method.

About the author

Kalsoom Bibi

Hello, I am a freelance writer and usually write for Linux and other technology related content