C ++ get size (in bytes) EOL

I am reading an ASCII text file. It is determined by the size of each field in bytes. For example. Each line consists of 10 bytes for a certain line, 8 bytes for a floating point value, 5 bytes for an integer, etc.

My problem is reading a newline character, which has a variable size depending on the OS (usually 2 bytes for windows and 1 byte for Linux, in my opinion).

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

For example, in python, I can do:

len(os.linesep) 
+8
c ++ newline eol
source share
2 answers

A time-worthy way to do this is to read the line.

Now the last char should be \n . Separate it. Then look at the previous character. It will be either \r or something else. If it is \r , separate it.

There are no other features in Windows [ascii] text files.

This works even if the file is mixed (for example, some lines \r\n , and some only \n ).

You can pre-do this on a few lines, just to make sure that you are not dealing with something strange.

After that, you now know what to expect from most of the file. But the strip method is an overall reliable way. On Windows, you can import a file from Unix (or vice versa).

+1
source share

I’m not sure that the translation takes place where you think. Take a look at the following code:

 ostringstream buf; buf<< std::endl; string s = buf.str(); int i = strlen(s.c_str()); 

After this is done on Windows, I == 1. Thus, determining the end of a line in std is 1 character. As others commented, this is the \ n character.

0
source share

All Articles