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

(Romina) #1
}
fclose(fptr); // Always close your files
return(0);
}

feof() returns a true condition if you just read the last line from the file. The feof() really isn’t
needed in the previous program because we know exactly what the bookinfo.txt contains. (We
just created the file in an earlier program.) We know how many lines are in the files, but you should
generally use feof() when reading from disk files. You often don’t know exactly how much data
the file contains because other people using other programs might have added data to the file.


Warning

In the fprintf() function, the file pointer goes at the beginning of the function. In
the fgets() function, the file pointer goes at the end. There’s nothing like
consistency!

You also can use an fscanf() to read individual numeric values from a data file if you wrote the
values with a corresponding fprintf().


You can add to a file by opening the file in append mode and outputting data to it. The following
program adds the line More books to come! to the end of the book info.txt data file:


Click here to view code image


// Example program #3 from Chapter 28 of Absolute Beginner's Guide
// to C, 3rd Edition
// File Chapter28ex3.c
/* The program opens the existing book info file from the first
example of chapter 28, and adds a line to the end. */
#include <stdio.h>
#include <stdlib.h>
FILE * fptr;
main()
{
fptr = fopen("C:\\users\\DeanWork\\Documents\\BookInfo.txt","a");
if (fptr == 0)
{
printf("Error opening the file! Sorry!\n");
exit (1);
}
// Adds the line at the end
fprintf(fptr, "\nMore books to come!\n");
fclose(fptr); // Always close your files
return(0);
Free download pdf