Learn to read from and write to text files using formatted input and output functions.
For working with human-readable text files, C provides the `fprintf()` and `fscanf()` functions, which are the file-based counterparts to the console functions `printf()` and `scanf()`. They allow you to write and read formatted data to and from files, making it easy to store text, numbers, and other data in a structured way. The `fprintf()` function is used to write formatted data to a file. Its syntax is very similar to `printf`, with one key difference: its first argument is a `FILE` pointer that specifies the file to write to. For example, `fprintf(fp, "Name: %s, Age: %d\n", name, age);` would write the formatted string to the file pointed to by `fp`. This is incredibly useful for creating log files, configuration files, or reports. The `fscanf()` function is used to read formatted data from a file. Like `scanf`, it reads characters from the stream, interprets them according to a format string, and stores the results in the arguments that you provide as pointers. Its first argument is also the `FILE` pointer. For instance, `fscanf(fp, "%s %d", name, &age);` would attempt to read a string and an integer from the file `fp` and store them in the `name` and `age` variables. `fscanf` returns the number of items successfully read and assigned, which is useful for checking if the read operation succeeded and for detecting the end of the file. These two functions are the go-to tools for I/O operations on plain text files.