Hi
My program reads a CSV file.
So I used fgets to read one line at a time.
But now the interface specification says that it is possible to find NULL characters in few of the columns.
So I need to replace fgets with another function to read from the file
Any suggestions?
Hi My program reads a CSV file. So I used fgets to read one
Share
fgetsworks perfectly well with embedded null bytes. Pre-fill your buffer with\n(usingmemset) and then usememchr(buf, '\n', sizeof buf). IfmemchrreturnsNULL, your buffer was too small and you need to enlarge it to read the rest of the line. Otherwise, you can determine whether the newline you found is the end of the line or the padding you pre-filled the buffer with by inspecting the next byte. If the newline you found is at the end of the buffer or has another newline just after it, it’s from padding, and the previous byte is the null terminator inserted byfgets(not a null from the file). Otherwise, the newline you found has a null byte after it (terminator inserted byfgets, and it’s the end-of-line newline.Other approaches will be slow (repeated
fgetc) or waste (and risk running out of) resources (loading the whole file into memory).