Presentation is loading. Please wait.

Presentation is loading. Please wait.

Line at a time I/O with fgets() and fputs()

Similar presentations


Presentation on theme: "Line at a time I/O with fgets() and fputs()"— Presentation transcript:

1 Line at a time I/O with fgets() and fputs()
The fgets(buffer_address, buf_size, file) function can be used to read from a stream until either: a newline character '\n' = 10 = 0x0a is encountered, or the specified number of characters - 1 has been read, or end of file is reached. fgets() will append the NULL character to whatever it reads in.

2 Line at a time input and output
Since fgets() will read in multiple characters it is not possible to assign what it reads to a single variable of type char. Thus a pointer to a buffer must be passed (as was the case with scanf()). The fputs() function writes a NULL terminated string to a stream (after stripping off the NULL). The following example is yet another cat program, but this one works one line at a time.

3 Line at a time input and output
#include <stdio.h> #include <stdlib.h> #include <string.h> int main() { unsigned char *buff = NULL; int line = 0; buff = malloc(1024); // alloc storage to hold data if (buff == 0) exit(1); while (fgets(buff, 1024, stdin) != 0) fputs(buff, stdout); fprintf(stderr, "%d %d \n", line, strlen(buff)); line += 1; } free(buff); // release the storage malloc allocated

4 Line at a time input and output
Here buff is declared a pointer and the storage which will hold the data is allocated with malloc() Alternatively we could have declared unsigned char buff[1024] and not used malloc()

5 Line at a time input and output
Here is the output that went to stderr. Note that each line that appeared empty has length 1 (the newline character itself) and the lines that appear to have length 1 actually have length 2. 0 12 1 1 2 19 3 20 4 1 5 7 6 2 7 24 8 18 9 1 10 24 11 18 12 15 13 1 14 41 15 5 16 27 17 55 18 17 19 4 20 2


Download ppt "Line at a time I/O with fgets() and fputs()"

Similar presentations


Ads by Google