Bifalgorithm post · Computer science one · Plaintext Files

How do fprintf() and fscanf() read from and write to plaintext files?

How do fprintf() and fscanf() read from and write to plaintext files? (Computer science one · Plaintext Files) — "When a file is opened, the file pointer retur…

Ideas in this flowchart

  • File-based input and output in C
  • When opened with fopen(), the file pointer initially points to the beginning and advances during reading or writing.
  • Plaintext files are processed with fprintf() for output and fscanf() for input.
  • fprintf() writes formatted data to a specified file.
  • fscanf() reads formatted data from a specified file.
  • fprintf() and fscanf() generalize printf() and scanf() for arbitrary files.
  • Standard input and output are also files, so they can be read from and written to.
  • The first argument specifies the file used for output or input.
  • Example output: fprintf(output, ...) writes text and the values x = 10 and y = 3.14.
  • Example input: fscanf(input, ...) reads integer data into x and double data into y.
  • fprintf(stdout, ...) is equivalent to using printf() for standard output.
  • fscanf(stdin, ...) is equivalent to using scanf() for standard input.
Feed/

How do fprintf() and fscanf() read from and write to plaintext files?

No cover

Channel

Computer science one

1 page

"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);"

Flowchart preview
👍
0
0 comments0 shares

Sign in to view and post comments.