gtpc2m2i | C/C++ Language Support User's Guide |
This function reads a string from a stream.
Format
#include <stdio.h> char *fgets(char *string, int n, FILE *stream);
This function reads bytes from a stream pointed to by stream into an array pointed to by string, starting at the position indicated by the file position indicator. Reading continues until the number of characters read is equal to n-1, or until a new-line character (\n), or until the end of the stream, whichever comes first. The fgets function stores the result in string and adds a null character (\0) to the end of the string. The string includes the new-line character, if read.
The fgets function has the same restriction as any read operation for a read immediately following a write or a write immediately following a read. Between a write and a subsequent read, there must be an intervening flush or reposition. Between a read and a subsequent write, there must be an intervening reposition unless an EOF has been reached.
Normal Return
If successful, the fgets function returns a pointer to the string buffer.
Error Return
If unsuccessful, the fgets function returns a NULL pointer.
If n is less than or equal to 0, the fgets function indicates a domain error and errno is set to EDOM to indicate the cause of the failure.
If n equals 1 (which indicates a valid result), the string buffer has room only for the null terminator; nothing is physically read from the file. (Such an operation is still considered a read operation, so it cannot immediately follow a write operation unless there is an intervening flush or reposition operation first.)
If n is greater than 1, the fgets function will only fail if an I/O error occurs or if end-of file (EOF) is reached, and no data is read from the file.
The ferror and feof functions are used to distinguish between a read error and an EOF.
If EOF is reached after data has already been read into the string buffer, the fgets function returns a pointer to the string buffer to indicate success. A subsequent call would result in NULL being returned because EOF would be reached without any data being read.
Programming Considerations
None.
Examples
The following example gets a line of input from a data stream. It reads no more than MAX_LEN - 1 characters or up to a new-line character from the stream.
#include <stdio.h> #define MAX_LEN 100 int main(void) { FILE *stream; char line[MAX_LEN], *result; stream = fopen("myfile.dat","r"); if ((result = fgets(line,MAX_LEN,stream)) != NULL) printf("The string is %s\n", result); if (fclose(stream)) printf("fclose error\n"); }
Related Information
See Appendix E, Programming Support for the TPF File System for more information about TPF File System C Functions.