Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ get the size (in bytes) of EOL

Tags:

c++

newline

eol

I am reading an ASCII text file. It is defined by the size of each field, in bytes. E.g. Each row consists of a 10 bytes for some string, 8 bytes for a floating point value, 5 bytes for an integer and so on.

My problem is reading the newline character, which has a variable size depending on the OS (usually 2 bytes for windows and 1 byte for linux I believe).

How can I get the size of the EOL character in C++?

For example, in python I can do:

len(os.linesep)
like image 624
jramm Avatar asked Jan 05 '16 07:01

jramm


1 Answers

The time honored way to do this is to read a line.

Now, the last char should be \n. Strip it. Then, look at the previous character. It will either be \r or something else. If it's \r, strip it.

For Windows [ascii] text files, there aren't any other possibilities.

This works even if the file is mixed (e.g. some lines are \r\n and some are just \n).

You can tentatively do this on few lines, just to be sure you're not dealing with something weird.

After that, you now know what to expect for most of the file. But, the strip method is the general reliable way. On Windows, you could have a file imported from Unix (or vice versa).

like image 188
Craig Estey Avatar answered Sep 30 '22 00:09

Craig Estey