C Programming

How To Read a Text File and Print All Strings in C

Reading a text file and printing all strings is a key task which is frequently done by C programmers. It is important to understand the basics of reading a text file in C and how to print the strings from it before attempting this task.

The reading of a text file and printing of all strings it contains will be demonstrated using C programming in this article.

Read a Text File and Print all Strings in C

There are four functions to read a text file and print all strings in C, which are as follows:

Method 1: fread() Function

Data is read from the file and stored in a buffer using the C function fread(). In order to count elements in an array buffer, the fread() method reads from the input stream provided as the function parameter. As each character function reads, the file position indicator for the specified input stream moves forward.

The fread() method in C has the syntax.

size_t fread(void * array_buffer, size_t size, size_t count, FILE * file_stream)

 

Let’s look at fread() function parameters in further detail:

array buffer: Data is temporarily held in a computer’s buffer, a memory space. This argument is a pointer referring to the place in memory of the buffer that will contain the data read from the input stream.

size: This argument instructs the function of how many bytes of data will be read from the input stream for each block.

count: It specifies how many characters will be read from the data input stream.

file_stream: It is a pointer referring to a FILE object.

#include <stdio.h>
#include <stdlib.h>
int main() {
   FILE *file;
   char buffer[100];
   file = fopen("C_File.txt", "r");
   if (file == NULL) {
      printf("Error: could not open file\n");
      return 1;
   }
   int count=fread(&buffer, sizeof(char), 100, file);
   fclose(file);
   printf("Data read from file is: %s\n", buffer);
   printf("Number of elements read: %d", count);
   fclose(file);
   return 0;
}

 

In this example, we define a character array buffer of size 100 before utilizing fopen() to open the text file C_File.txt in read mode. Using an if statement, we determine if the file was opened successfully. The following step is to read up to 100 bytes of data from the file using fread(). The target buffer, in this instance the buffer array, is the first parameter to fread(). The second argument, sizeof, determines the size of each item to be read as we are reading in characters. The third input is the quantity to be read, which in this case is 100. The file pointer is the fourth parameter. Lastly, we use printf() to print the data read from the file and fclose() to close the file. Running this program would result in results like this, if C_File.txt:

Output

Method 2: fgets() Function

The C language’s fgets() method reads n characters from the stream into the string str. The fgets() method continues to read characters from the stream until (n-1) characters have been read, a newline character has been detected, or the end of the file (EOF) has been reached.

#include <stdio.h>
int main() {
   FILE *file;
   char buffer[100];
   file = fopen("C_File.txt", "r");
   if (file == NULL) {
      printf("Error: could not open file\n");
      return 1;
   }
   while (fgets(buffer, 100, file)) {
      printf("String read from file: %s", buffer);
   }
   fclose(file);
   return 0;
}

 

This example uses fopen() to open a text file called C_File.txt in read mode after first declaring a character array buffer of size 100. Using an if statement, we determine if the file was opened successfully. After that, we employ a while loop and fgets() to read lines of text from the file using a file pointer. Using printf() within the loop, we print each line of text. Running this program would provide the output:

Output

Method 3: fscanf() Function

A standard library method called fscanf() accepts an array of parameters and transforms them into values your application may utilize. While reading from the file, it will return the format string in place of anything it anticipates seeing within. To prevent your software from interpreting the format string as part of its own syntax, it must be surrounded in quotes (“”).

#include <stdio.h>
int main() {
   FILE *file;
   int num1, num2, num3;
   file = fopen("C_File.txt", "r");
   if (file == NULL) {
      printf("Error: could not open file\n");
      return 1;
   }
   fscanf(file, "%d %d %d", &num1, &num2, &num3);
   printf("Numbers read from the file are: %d, %d, %d\n", num1, num2, num3);
   fclose(file);
   return 0;
}

 

This example opens the file C_File.txt in read mode by first declaring 3 int variables, num1, num2, and num3. Using an if statement, we determine if the file was opened successfully. The following step is to read three numbers from the file using fscanf() and the %d format specifier. The variables num1, num2, and num3 are where the values are kept. Lastly, we use printf() to output the values of these variables and fclose() to close the file. Running this program would result in the results shown below:

Output

Method 4: fgetc() Function

A file can be read character by character using the fgetc() function. The ASCII code for the character this function reads is returned by this function. The character from the file pointer’s specified location is returned. The following character is read once the character has been read, according to the file pointer. This method returns an EOF file if the pointer is at the end of file or if there is a problem.

#include <stdio.h>
int main() {
   FILE *file;
   char c;
   file = fopen("C_File.txt", "r");
   if (file == NULL) {
      printf("Error: could not open file\n");
      return 1;
   }
   while ((c = fgetc(file)) != EOF) {
      printf("%c", c);
   }
   fclose(file);
   return 0;
}

 

In this instance, we use the fopen() command to open the text file C_File.txt in read mode. Using an if statement, we determine if the file was opened successfully. After that, we employ a while loop and fgetc() to read characters from the file. The character received from the file is assigned to the variable c inside the loop before being printed using printf (). The loop keeps running until the EOF (End of File) constant detects the end of the file. Running this program would get the following results, if C_File.txt contains the word “Linuxhint”.

Output

Conclusion

By using the steps outlined above, C can be used to read a text file and print all strings it contains. It begins by using the fopen() system call to open the file, followed by the use of fscanf(), fread(), fgets(), fgetc() to read the data. Afterwards, the file is closed using fclose() and a for loop is used to print the strings. By employing these techniques, C can be used to help read and print data in an efficient manner.

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.