Specifically, the code sample here works great, but only when the string is stored in a file.
Sometimes I need it to process a generated string (stored in a string variable), but I'm having trouble convincing fgets's third parameter to work with string variables because it's a pointer to a FILE structure.
Or perhaps there's a functional equivalent to fgets that may be used on strings?
Any suggestions? Thanks!
(Read String from File) In the C Programming Language, the fgets function reads characters from the stream pointed to by stream. The fgets function will stop reading when n-1 characters are read, the first new-line character is encountered in s, or at the end-of-file, whichever comes first.
fgets() function in C The function reads a text line or a string from the specified file or console. And then stores it to the respective string variable. Similar to the gets() function, fgets also terminates reading whenever it encounters a newline character.
The fgets() function reads characters from the current stream position up to and including the first new-line character (\n), up to the end of the stream, or until the number of characters read is equal to n-1, whichever comes first.
The C library function char *fgets(char *str, int n, FILE *stream) reads a line from the specified stream and stores it into the string pointed to by str. It stops when either (n-1) characters are read, the newline character is read, or the end-of-file is reached, whichever comes first.
The standard C library does not provide that functionality.
But AT&T's safe/fast I/O library does enable memory streams and also provides wrapper code to use the FILE API with their extensions. The last update is from Feb 2005 so either they finally worked out all the bugs or they can no longer afford to maintain it now that Luke Wilson is on the payroll :-(
The package can be downloaded here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With