C Programming Absolute Beginner's Guide (3rd Edition)

(Romina) #1
Tip

Think of the f at the beginning of fputs() and fgets() as standing for file.
puts() and gets() go to the screen and keyboard, respectively; fputs() and
fgets() write and read their data from files.

Unlike gets(), fgets() requires that you specify a maximum length for the array you’re reading
into. You might read past the end of the file (producing an error) if you’re not careful, so be sure to
check for the location of the end of the file.


fgets() reads one line at a time. If you specify more characters to read in the fgets() than
actually reside on the file’s line you’re reading, fgets() stops reading the line of data as long as
the file’s lines end with a newline character. The previous program that created the bookinfo.txt
file always wrote \n at the end of each line so that subsequent fgets() functions could read the
file line by line.


The following program loops through a file (in this case, the bookinfo.txt created in the last
example) and prints the info on the screen.


Click here to view code image


// Example program #2 from Chapter 28 of Absolute Beginner's Guide
// to C, 3rd Edition
// File Chapter28ex2.c
/* The program takes the book info file from the first example of
chapter 28; also reads each line from the file and outputs it to the
screen. */
#include <stdio.h>
#include <stdlib.h>
FILE * fptr;
main()
{
char fileLine[100]; // Will hold each line of input
fptr = fopen("C:\\users\\DeanWork\\Documents\\BookInfo.txt","r");
if (fptr != 0)
{
while (!feof(fptr))
{
fgets(fileLine, 100, fptr);
if (!feof(fptr))
{
puts(fileLine);
}
}
}
else
{
printf("\nError opening file.\n");
Free download pdf