Equivalent to fgets in a buffer?

I originally parsed the file line by line using fgets. Now I changed it so that I already have the whole file in the buffer. I still like to read this buffer line by line for parsing purposes. Is there something for this, or do I need to make a loop that checks for a 0x0A char at this point?

+4
source share
4 answers

memchr (with a small amount of shell native code ending in memcpy ) is the exact equivalent - for example, fgets it takes the maximum length that it will process (should be min the remaining input buffer the size and size of your output buffer) and scans until until it reaches the desired character (which will be '\n' ) or ends outside of the I / O space.

Note that for data already in the buffer in memory, you can skip the step of copying to a separate output buffer, unless you need to end output zero without changing the input. Many novice C programmers often make the mistake of thinking that they need zero completion when it would be quite simple to improve some of your interfaces in order to take a pair (pointer, length) that allows you to pass / process substrings without copying them. For example, you can pass them to printf using: printf("%.*s", (int)length, start);

+5
source

You can use the sscanf function for this. If you really need a whole line, something like this should do the trick:

 sscanf(your_buffer, "%50[^\n]", line); 

(This will read lines no longer than 50 characters. As always, be careful with terminators of length and 0 And check the sscanf return value if something went wrong.)

You can use pointer arithmetic to move your buffer (just add the "returned" line length + 1).

+2
source

There is sscanf, which may or may not work for you.

0
source

If you are looking for C functions, strtok() and strsep() will split the string by the specified character.

0
source

All Articles