16.4: Line Input and Output (fgets, fputs, etc.)

The function

	char *gets(char *line)
reads the next line of text (i.e. up to the next \n) from the standard input and places the characters (except for the \n) in the character array pointed to by line. It returns a pointer to the line (that is, it returns the same pointer value you gave it), unless it reaches end-of-file, in which case it returns a null pointer. It is assumed that line points to enough memory to hold all of the characters read, plus a terminating \0 (so that the line will be usable as a string). Since there's usually no way for anyone to guarantee that the array is big enough, and no way for gets to check it, gets is actually a useless function, and no serious program should call it.

The function

	char *fgets(char *line, int max, FILE *fp)
is somewhat more useful. It reads the next line of input from the stream fp and places the characters, including the \n, in the character array pointed to by line. The second argument, max, gives the maximum number of characters to be written to the array, and is usually the size of the array. Like gets, fgets returns a pointer to the line it reads, or a null pointer if it reaches end-of-file. Unlike gets, fgets does include the \n in the string it copies to the array. Therefore, the number of characters in the line, plus the \n, plus the \0, will always be less than or equal to max. (If fgets reads max-1 characters without finding a \n, it stops reading there, copies a \0 to the last element of the array, and leaves the rest of the line to be read next time.) Since fgets does let you guarantee that the line being read won't go off the end of the array, you should always use fgets instead of gets. (If you want to read a line from standard input, you can just pass the constant stdin as the third argument.) If you'd rather not have the \n retained in the input line, you can either remove it right after calling fgets (perhaps by calling strchr and overwriting the \n with a \0), or maybe call the getline or fgetline function we've been using instead. (See chapters 6 and 12; these functions are also handy in that they return the length of the line read. They differ from fgets in their treatment of overlong lines, though.)

The function

	int puts(char *line)
writes the string pointed to by line to the standard output, and writes a \n to terminate it. It returns a nonnegative value (we don't really care what the value is) unless there's some kind of a write error, in which case it returns EOF.

Finally, the function

	int fputs(char *line, FILE *fp)
writes the string pointed to by line to the stream fp. Like puts, fputs returns a nonnegative value or EOF on error. Unlike puts, fputs does not automatically append a \n.


Read sequentially: prev next up top

This page by Steve Summit // Copyright 1996-1999 // mail feedback