Bifalgorithm post · Computer science one · Binary Files

How can you read a text file one line at a time?

How can you read a text file one line at a time? (Computer science one · Binary Files) — "22. File I/O\n\n4 //read the first line\n\n5 char *s = fgets(line, 10…

Ideas in this flowchart

  • File I/O
  • Line-oriented reading uses fgets to retrieve data from an input file.
  • The first fgets call reads the first line into the line buffer.
  • The loop continues while fgets returns a non-NULL pointer.
  • The current buffer is processed during each loop iteration.
  • The trailing newline character is removed from line.
  • The example prints the current line.
  • After processing, fgets reads the next line.
  • When fgets returns NULL, line reading ends.
  • The alternative fgetc(FILE *stream) reads one character at a time.
  • fgetc returns the character as an int.
Feed/

How can you read a text file one line at a time?

No cover

Channel

Computer science one

1 page

"22. File I/O\n\n4 //read the first line\n\n5 char *s = fgets(line, 1000, input);\n\n6 while(s != NULL) {\n\n7\n\n8 //chomp the endline character from line:\n\n9 line[strlen(line)-1] = '\\0';\n\n10\n\n11 //process the current buffer\n\n12 //for demonstration, we simply print it:\n\n13 printf(\"line = %s\n\n\", line);\n\n14\n\n15 //read the next line\n\n16 s = fgets(line, 1000, input);\n\n17 }\n\nA similar function, int fgetc(FILE *stream) allows us to get a single character from the input file (returned as an int ) if we prefer to read character by character."

Flowchart preview
👍
0
0 comments0 shares

Sign in to view and post comments.