Concept
How do fprintf() and fscanf() read from and write to plaintext files?
ComputerScienceOne / Plaintext Files
"When a file is opened, the file pointer returned by fopen() initially points to the beginning of the file. As you read from it or write to it, the pointer advances through the file content.\n\nTo process a plaintext file we use two functions, fprintf() for output and fscanf() for input. These two functions should look familiar. They work almost exactly the same as printf() and scanf() that work with the standard output and standard input respectively. In fact, the standard in/out are both files so it makes sense that they can be read from/written to. The f prefixed versions are simply generalizations that can be used for any file. The only difference is that the first argument for these two functions is the file you want to output to or read from.\n\nint x = 10;\n\ndouble y = 3.14;\n\n//write to a plaintext file\n\nfprintf(output, \"Hello World!\n\n\");\n\nfprintf(output, \"x = %d, y = %f\n\n\", x, y);\n\n//read from a plaintext file\n\nfscanf(input, \"%d\", &x);\n\nfscanf(input, \"%lf\", &y);\n\n//these are equivalent to printf, scanf:\n\nfprintf(stdout, \"Please enter an integer:\");\n\nfscanf(stdin, \"%d\", &x);"
Related Ideas
- How do fread and fwrite read and write binary data?ComputerScienceOne · Binary Files
- How can you read a text file one line at a time?ComputerScienceOne · Binary Files
- When should data be stored as binary or text files?ComputerScienceOne · Buffered and Unbuffered
- How does scanf() read integer, character, and floating-point input in C?ComputerScienceOne · Basic I/O
- What is 22?ComputerScienceOne · Opening Files
- How do you write and read binary data in C?ComputerScienceOne · Closing Files
- How do sscanf() and sprintf() work with strings?ComputerScienceOne · Tokenizing
- How should you close files in C?ComputerScienceOne · Closing Files