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);
fprintf() Signifiers | |
---|---|
Signifier | Meaning |
d | integer |
f | floating point number |
hd | short integer |
ld | long integer |
hu | unsigned short integer |
u | unsigned integer |
lu | unsigned long integer |
lf | double |
Lf | long double (not always available) |
c | character |
s | string |
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.
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. | |
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. | |
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. | |
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. | |
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.