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

(Romina) #1

to a file, you can use fprintf(). fprintf() is easy because it’s just a printf() with a file
pointer at the beginning of its parentheses. The following program creates a file and writes some data
to it using fprintf():


Click here to view code image


// Example program #1 from Chapter 28 of Absolute Beginner's Guide
// to C, 3rd Edition
// File Chapter28ex1.c
/* The program takes the book info program from chapter 27 and
writes the info to a file named bookinfo.txt. */
//First include the file with the structure definition
#include "bookinfo.h"
#include <stdio.h>
#include <stdlib.h>
FILE * fptr;
main()
{
int ctr;
struct bookInfo books[3]; // Array of three structure variables
// Get the information about each book from the user
for (ctr = 0; ctr < 3; ctr++)
{
printf("What is the name of the book #%d?\n", (ctr+1));
gets(books[ctr].title);
puts("Who is the author? ");
gets(books[ctr].author);
puts("How much did the book cost? ");
scanf(" $%f", &books[ctr].price);
puts("How many pages in the book? ");
scanf(" %d", &books[ctr].pages);
getchar(); //Clears last newline for next loop
}
// Remember when typing your filename path to double up the
// backslashes or C will think you are putting in a conversion
// character
fptr = fopen("C:\\users\\DeanWork\\Documents\\BookInfo.txt","w");
// Test to ensure that the file opened
if (fptr == 0)
{
printf("Error--file could not be opened.\n");
exit (1);
}
// Print a header line and then loop through and print the info
// to your file, but this time this printout will be in your
// file and not on the screen.
Free download pdf