Read a string of characters from a stream
#include <stdio.h>
char* fgets( char* buf,
size_t n,
FILE* fp );
libc
The fgets() function reads a string of characters from the stream specified by fp, and stores them in the array specified by buf.
It stops reading characters when:
Or:
Or:
The newline character isn't discarded. A null character is placed immediately after the last character read into the array.
| Don't assume the presence of a newline character in every string that is
read with fgets().
A newline character isn't be present when more than
n-1 characters occur before the newline.
Also, a newline character might not appear as the last character in a file when the end-of-file is reached. |
The same pointer as buf for success, or NULL if the stream is at the end-of-file or an error occurs (errno is set).
#include <stdio.h>
#include <stdlib.h>
int main( void )
{
FILE *fp;
char buffer[80];
fp = fopen( "file", "r" );
if( fp != NULL ) {
while( fgets( buffer, 80, fp ) != NULL ) {
fputs( buffer, stdout );
}
fclose( fp );
return EXIT_SUCCESS;
}
return EXIT_FAILURE;
}
| Safety: | |
|---|---|
| Cancellation point | Yes |
| Interrupt handler | No |
| Signal handler | No |
| Thread | Yes |
errno, fopen(), getc(), gets(), fgetc()