Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can C's fgets be coaxed to work with a string *not* from a file?

Tags:

c

string

file

fgets

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!

like image 918
Monte Hurd Avatar asked Jan 15 '10 02:01

Monte Hurd


People also ask

Can fgets read from file?

(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.

How does fgets in C work?

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.

How does fgets () read the data from a file?

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.

How do I input string in fgets?

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.


1 Answers

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.

like image 191
R Samuel Klatchko Avatar answered Nov 17 '22 10:11

R Samuel Klatchko