MoonBun
MoonBun

Reputation: 4402

Reading lines in c with windows.h

I need to use system-calls of windows.h to read a file which I get from command line. I can read to whole file to buffer using ReadFile() and then cut the buffer at the first \0, but how can I read only one line? Also I need to read the last line of the file, Is this possible without reading the whole file into buffer, because maybe the file is 4gb or more so I won't be able to read it. So anyone knows how to read it by lines?

Upvotes: 4

Views: 670

Answers (3)

Hans Passant
Hans Passant

Reputation: 942408

Don't "cut the buffer at the first \0", ReadFile doesn't return a zero-terminated string. It reads raw bytes. You have to pay attention to the value returned through the lpNumberOfBytesRead argument. It will be equal to the nNumberOfBytesToRead value you pass unless you've reached the end of the file.

Now you know how many valid bytes are in the buffer. Search them for the first '\r' or '\n' byte to find the line terminator. Copy the range of bytes to a string buffer supplied by the caller and return. The next time you read a line, start where you left off previously, past the line terminator. When you don't find the line terminator then you have to copy the bytes in the buffer and call ReadFile() again to read more bytes. That makes the code a bit tricky to get right, excellent exercise otherwise.

Upvotes: 1

AndersK
AndersK

Reputation: 36092

If you have an idea of how long lines are then you are in business, make a buffer that is a bit larger than max line.

ReadFile read a number of bytes and cut buffer at first end of line (\n)

Use LZSeek to position at end of file, then move back a line of bytes and look for end of line, start there and read rest of line.

Upvotes: 1

Jon
Jon

Reputation: 437854

ReadFile is a particularly poor choice for what you want to do. Are you allowed to use fgets? That would be much easier to use in your case.

Upvotes: 0

Related Questions