fgets()
QNX SDP8.0C Library ReferenceAPIDeveloper
Read a string from a stream
Synopsis:
#include <stdio.h>
char* fgets( char* buf,
int n,
FILE* fp );
Arguments:
- buf
- A pointer to a buffer in which fgets() can store the bytes that it reads.
- n
- The maximum number of bytes to read.
- fp
- The stream from which to read the string.
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included automatically.
Description:
The fgets() function reads a string of bytes from the stream specified by fp, and stores them in the array specified by buf.
It stops reading bytes when:
- the end-of-file is reached
Or:
- a newline (
'\n'
) character is readOr:
- n-1 bytes have been read.
The newline character isn't discarded. A null character is placed immediately after the last byte read into the array.
Note:
Don't assume that there's a newline character in every string that you
read with fgets().
A newline character isn't present if there are more than
n-1 bytes before the newline.
Also, a newline character might not appear as the last character in a file when the end-of-file is reached.
Returns:
- If successful, fgets() returns buf.
- If the stream is at the end of the file, fgets() sets the end-of-file indicator for the stream and returns NULL.
- If an error occurred, fgets() sets the error indicator for the stream, sets errno, and returns NULL.
Examples:
#include <stdio.h>
#include <stdlib.h>
int main( void )
{
FILE *fp;
char buffer[80];
char *ret;
fp = fopen( "file", "r" );
if (fp == NULL) {
perror ("fopen()");
return EXIT_FAILURE;
}
while (1) {
ret = fgets( buffer, 80, fp );
if (ret == NULL) {
if (feof( fp )) {
// We're at the end of the file.
return EXIT_SUCCESS;
} else {
// An error occurred.
perror ("fgets()");
return EXIT_FAILURE;
}
}
fputs( buffer, stdout );
}
}
Classification:
Safety: | |
---|---|
Cancellation point | Yes |
Signal handler | No |
Thread | Yes |
Page updated: