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

(Romina) #1
fprintf(fptr, "\n\nHere is the collection of books: \n");
for (ctr = 0; ctr < 3; ctr++)
{
fprintf(fptr, "#%d: %s by %s", (ctr+1), books[ctr].title,
books[ctr].author);
fprintf(fptr, "\nIt is %d pages and cost $%.2f",
books[ctr].pages, books[ctr].price);
fprintf(fptr, "\n\n");
}
fclose(fptr); // Always close your files
return(0);
}

If you ran this program and looked at the contents of the file named bookinfo.txt (just find the
file and double-click it, and Notepad should open it), you would see the book info you entered.
Here’s what mine looked like:


Click here to view code image


Here is the collection of books:
#1: 10 Count Trivia by Dean Miller
It is 250 pages and costs $14.99
#2: Moving from C to C++ by Greg Perry
It is 600 pages and costs $39.99
#3: The Stand by Stephen King
It is 1200 pages and costs $24.99

Miller, Perry, and King—nice to see the three great authors of our time collected into one file! The
nice thing about reusing the program from Chapter 27, “Setting Up Your Data with Structures,” is that
it shows how easily you can adapt what you’ve already learned (and programs that you’ve already
written) to file work. All this took was declaring the file pointer, opening the file (and making sure it
opened properly), and changing the printf() statements to fprintf() statements for any output
you wanted to go to the file instead of the screen.


Warning

Opening a file in "w" mode overwrites an existing file with the same name. So if you
run the previous program twice, the file will have only your data from the second run.
If you want to build on to the file and keep the previous data, you need to open the file
in "a" mode.

Now that you can write data to a file, how would you go about getting that information? Use
fgets() to read the contents of the file. fgets() is nothing more than a gets() that you can
direct to a disk file. fgets() reads lines from a file into character arrays (or allocated heap
memory pointed to with a character pointer).

Free download pdf