In the preceding chapter, we utilized the ‘w’ and ‘a’ modes within the fopen() function to write to a file.
To read from a file, employ the ‘r’ mode.
FILE *fptr;
// Open a file in read mode |
This will open the filename.txt file for reading.
Reading a file in C involves a few steps, but don’t worry! We’ll walk you through it step-by-step. |
Subsequently, we’ll need to create a string of sufficient size to accommodate the content of the file.
For instance, let’s generate a string capable of holding up to 100 characters:
FILE *fptr;
// Open a file in read mode // Store the content of the file |
To extract the content of filename.txt, we can employ the fgets() function.
The fgets() function accepts three parameters:
fgets(myString, 100, fptr); |
Now, we can print the string, resulting in the output of the file’s content:
FILE *fptr;
// Open a file in read mode // Store the content of the file // Read the content and store it inside myString // Print the file content // Close the file |
Hello World! |
Note: The fgets
function reads only the first line of the file. Recall that filename.txt
contains two lines of text.
To read each line of the file, you can employ a while loop.
FILE *fptr;
// Open a file in read mode // Store the content of the file // Read the content and print it // Close the file |
|
Attempting to open a non-existent file for reading will result in the fopen() function returning NULL.
Tip: As a best practice, it’s advisable to use an if statement to check for NULL, and print appropriate text instead, particularly when the file does not exist.
FILE *fptr; // Open a file in read mode // Print some text if the file does not exist // Close the file |
If the file is not found, the following text will be printed:
|
Considering this, we can develop a more sustainable code by revisiting our previous example of “reading a file.”
If the file exists, read and print its contents. If the file does not exist, display a message.
FILE *fptr;
// Open a file in read mode // Store the content of the file // If the file exist // Read the content and print it // If the file does not exist // Close the file |
|