Writing to Files

Once you've opened a file for writing (meaning that you used either the w or a mode, or a variant thereof), you can write data to it. To do so, you can use the fprintf() function, which works like printf() except that it takes a file pointer as its first argument:

fprintf (file_pointer, formatting,
					extra_arguments);

The formatting signifiers are exactly the same as those used with printf() and scanf() (Table 12.2). So, to write an unsigned integer to a file, you would code

fprintf (fp, "%u", 30);

Table 12.2. The different signifiers used with printf(), sprintf(), and fprintf().
fprintf() Signifiers
SignifierMeaning
dinteger
ffloating point number
hdshort integer
ldlong integer
huunsigned short integer
uunsigned integer
luunsigned long integer
lfdouble
Lflong double (not always available)
ccharacter
sstring

As with the printf() function, you can include literal values (like punctuation and words) or newlines in the formatting area:

fprintf (fp, "%s
", name);

Here, the newline character will ensure that each time the fprintf() statement is executed, the data is written on its own line in the text file.

Our next example will take input from the keyboard in the form of a date and that day's high and low temperatures (Figure 12.3). This data will be stored in a text file to be read by the next example in the chapter.

Figure 12.3. The application's prompt indicates what information is to be keyed and in what format.


To write to files

1.
Create a new file or project in your text editor or IDE.

2.
Type the standard beginning lines of code (Script 12.2):

/* record_weather.c - Script 12.2 */
#include <stdio.h>

Script 12.2. The record_weather application takes three user input values (a date, the day's high temperature, and the day's low temperature) and writes them to a text file.


3.
Set the file path and name as a C preprocessor macro.

Again the actual syntax will depend on your operating system and where you want the file to be created. Here are possible examples for Mac OS X and Windows:

#define THEFILE
 "/Users/larry/Desktop/weather.txt"
#define THEFILE "C:\Documents and
 Settings\Larry Ullman\Desktop\
 weather.txt"

4.
Begin the main function and create a file pointer:

int main (void) {
FILE *fp;

5.
Define the required variables:

int high, low;
char date[11];

The first two variables are integers that will store the entered high and low temperatures. The date variable is a character array to store dates in the format YYYY-MM-DD, like 2005-01-01.

6.
Open the file for appended writing:

fp = fopen(THEFILE, "a");

This code is similar to that in the test application except that the a mode is used instead of w. By using a, each new record will be appended to the end of the file, rather than wiping out any existing data.

7.
Start a conditional based on the file pointer and prompt the user:

if (fp != NULL) {
     printf ("Enter a date, the high
 temperature, and the low
 temperature.
(YYYY-MM-DD ## ##):
 ");

The conditional is the same as it was before. If the file could be opened, then the user will be prompted for the required information (Figure 12.3).

8.
Handle the keyed input:

if (scanf ("%10s %d %d", date, &high,
 &low) == 3) {

Using the scanf() function, the application attempts to read one string (of up to 10 characters long) and two integers from the standard input. The string will be stored in date, which, as a character array, can be listed directly. The two integer values go into high and low, which, as numbers, must be referenced in their address form (&).

If scanf() successfully read in three items, the user entered the information Properly, so the conditional checks if the returned value is equal to 3.

See Chapter 5, “Standard Input and Output,” for more on the syntax of scanf().

9.
Write the data to the text file:

fprintf(fp, "%s %d %d
", date, high,
 low);

The fprintf() function will write the values to the text file. The formatting is simple: separating each value by a space and ending with a newline.

10.
Complete the scanf() conditional:

  printf ("The data has been
 written.
");
} else {
  printf ("The data was not in
 the proper format.
");
}

The first message completes the conditional if scanf() worked, indicating that the data was written to the file. If scanf() did not return a value of 3, the input was not of the proper format and the second message is printed to the screen.

11.
Complete the fp conditional:

} else {
    printf ("The file could not
 be opened.
");
    return 1;
}

If the application could not open the file for writing, there's no reason to continue. So, unlike the previous example, in this case an error message will be printed and the function will return the number 1 to indicate that a problem occurred (Figure 12.4). Because functions always stop running after a return statement, this effectively stops the application.

Figure 12.4. If the file could not be opened for appended writing, this is the result.


12.
Close the file:

if (fclose(fp) != 0) {
    printf ("The file could not
 be closed.
");
 }

Rather than indicating if the file was closed successfully, this code now indicates if it wasn't closed successfully. You can also use a return 1; line here, if you want.

13.
Complete the main function:

    getchar();
    getchar();
    return 0;
 }

The extra use of getchar() is to make the application stick around a while longer on Windows, after reading the user input. You could also use the discard_input function (see Chapter 7, “Creating Your Own Functions”) to get rid of extraneous input.

14.
Save the file as record_weather.c, compile, and debug as necessary.

15.
Run the application multiple times to populate the text file (Figures 12.5 and 12.6).

Figure 12.5. Adding a record to the weather file.


Figure 12.6. Entering another set of data for a particular date.


16.
Open the weather.txt file in any text editor to confirm that the data was written (Figure 12.7).

Figure 12.7. The text file contains all of the submitted records in the order they were entered.


The next example in this chapter will formally read the weather.txt file but you can quickly confirm that the process is working by using a text editor.

✓ Tips

  • The fprintf() function returns the number of characters written to a file or the number -1 if no writing occurred.

  • The fputc() function is an easy way to write a single character to a file:

    fputc ('B', fp);
    
  • You can also use the fputs() function to write a string to a file:

    fputs ("I like it.
    ", fp);
    
  • As far as C is concerned, the standard output, text files, printers, and many other things are all considered “files” that C writes to.


Documenting Your Files

Even though the text files in this chapter are written to and read from using a C application, there's something to be said for documenting their format. By doing so, if a user ever opens the data file, it will still have meaning. Or, future developers using your code will be better able to understand why data was written or read in a certain way.

One way to add documentation is to place comments in the C program itself. This will help out the programmer:

/* The text file stores data in the format:
YYYY-MM-DD ## ##

where the first number is the high temperature and the second is the low. */

A companion option is to add a line indicating the format at the top of the data file, like

DateHighLow
2004-08-299472
2004-08-309070

Then, when the C program reads the text file, you would have the application ignore the first line.

Finally, you could add comments to your text file, like this:

# This is weather.txt.
# It records the high and low
# temperatures for a particular date.

Again, you would then have your C application ignore lines beginning with #.


..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset