C Programming

How to Read a Text File in C

Text files are among the most widely used file types on computers. They may be utilized for a wide variety of tasks, such as storing text documents or program source codes. They are saved in the system with .txt extension. While working on C code, you may need to read a text file as a part of your project or to get help from the text file. Instead of going back to the location to read a text file, it’s better to read it inside a code.

This article discusses useful ways to read a text file in the C programming language.

Read a Text File in C

There are four methods to read a text file in C, which are.

Method 1: Using fscanf() Function to Read a Text File in C

The fscanf() function is a standard library function that takes in an array of arguments and converts them into values that can be used by your program. It finds a format string inside the file and returns a format string when reading from the file. The format string must be enclosed within quotes (“ ”) so that they do not get interpreted by your program as part of its own syntax.

The fscanf() function reads data into the places provided by the items in the argument-list. The argument-list entries must all point to variables whose types match the type specifiers in format-string.

It gives either EOF (end of file) or the number of variables with values assigned to them.

Let’s look at an example to read a text file using the fscanf() function:

#include <stdio.h>
int main()
{
    FILE* ptr = fopen("file_name.txt", "r");
    if (ptr == NULL) {
        printf("no such file exists.");
        return 0;
    }
    char buf[100];
    while (fscanf(ptr, "%s ", buf)== 1)
        printf("%s\n", buf);
    return 0;
}

In this code, fopen() function is used to open the file under the pointer variable ptr. fscanf() function is then used to read the file and then print its content.

Output

Method 2: Using fread() Function to Read a Text File in C

Data from the file is read by the Fread() method and stored in a buffer. Up to count items are read into an array buffer by the fread() function from the input stream, which is supplied as a function argument.

When the total number of items are successfully read, a size_t object is returned. If this value is different from the value specified by the program, either an error occurred or the end of the file was reached.

#include <stdio.h>
int main ()
{
    char buffer[33];
    FILE * stream;
    stream = fopen("file_name.txt", "r");
    int count = fread(&buffer, sizeof(char), 33, stream);
    fclose(stream);
    printf("Data read from the file: %s \n", buffer);
    printf("Number of elements read: %d", count);
    return 0;
}

In this code, the fopen() function is used to open the file and then the fread() function is then used to read the file and then print its content. 33 shows the number of characters it will read from the file.

Output

Method 3: Using fgets() Function to Read a Text File in C

With the fgets() function, a line is read from the specified stream and stored in the corresponding string variable. When (n-1) characters, the newline character, or the end of the file are read, or whichever occurs first, the program ends.If the function is successful, the same string is returned. The contents of string are retained in place and a null pointer occurs if the function hits End-of-File with no characters read.

In the event of a failure, it provides a null pointer.

#include <stdio.h>
int main () {
   FILE *fp;
   char str[60];
   fp = fopen("file.txt" , "r");
   if(fp == NULL) {
      perror("Error in opening file");
      return(-1);
   }
   if( fgets (str, 100, fp)!=NULL ) {
      puts(str);
   }
   fclose(fp);
   return(0);
}

In this code, file.txt file is opened by fopen() function and then fgets() function is then used to read the strings in the file and then print them. 100 shows the number of strings it will read.

Output

Method 4: Using fgetc() Function to Read a Text File in C

The fgtec() function is used to read the characters one by one. The function then returns the ASCII code of the character it has read. It returns the character that was present at the file pointer’s stated place. The file pointer then moves on to the next character. If there is an error or the pointer reaches the end of the file, this function returns an EOF (End-Of-File).

#include <stdio.h>
int main ()
{
    FILE *fp = fopen("file.txt","r");
    if (fp == NULL)
    return 0;
    do{
        char c = fgetc(fp);
        if (feof(fp))
            break ;
        printf("%c", c);
    } while(1);
    fclose(fp);
    return(0);
}

The “file.txt” file is opened by the fopen() function in this code under the pointer variable fp. The file’s characters are then read using the fgetc() method, which prints the characters that were read.

Output

Conclusion

Reading files is a necessity for every computer user, and especially for a developer, it is important that he can access files using his code. Therefore 4 methods are mentioned above in the article for reading a text file using C Language. fscanf() and fread() are used to read the files similarly, with the exception that fread() allows us to specify the number of character user wants to read, while fgets() is used to read a file line by line, and fgetc() is used to read a file character by character.

About the author

Hiba Shafqat

I am a Computer Science student and a committed technical writer by choice. It is a great pleasure to share my knowledge with the world in which I have academic expertise.