Tio Plato
Tio Plato

Reputation: 140

How to detect a line break in C++?

in windows, a line break is

\r\n

in linux,

\n

I don't want to change my code when it runs in different OS, I just want to recompile it directly.

So how to detect it in C++? Did the standard library defined a constant or function to detect it?

Upvotes: 2

Views: 4088

Answers (3)

senfen
senfen

Reputation: 907

Platform dependent details you need to encapsulate in abstraction. So just provide simple class TextInfo (?) and add there static function or maybe public static member which will return the line ending.

In this function you can add platform specific code with conditional compilation using preprocesor defines.

#ifdef WINDOWS
return "\r\n";
#endif
#ifdef LINUX
return "\n";
#endif

Now you just need to provide different target compilations (probably you already have that). For targets you need to add one more define to compile command (-D for gcc and /D for VS).

Then in code you are able to use TextInfo which will work fine for both systems. At any time you are able to add additional systems.

Upvotes: 1

VoidStar
VoidStar

Reputation: 5421

If you don't move your files between Windows/Linux, you should be fine.

However, in many circumstances, you have to read both conventions from both compiled programs. This is common with all sorts of documents and some network protocols. If this is the case, I recommend the following procedure:

  1. Scan for \r or \n.
  2. If char found is \r, then also look for \n immediately after it. If it exists, then consume it as part of the same newline.

This scanning procedure will accept files with CR, LF, and CR+LF line endings. It is analogous to what many encoding-detecting higher level string streams do.

Here is another answer which outlines this procedure in code for istream: Getting std :: ifstream to handle LF, CR, and CRLF?

Upvotes: 1

paxdiablo
paxdiablo

Reputation: 881563

You shouldn't have to change your code. Each implementation will correctly handle it's own line endings.

Provided each platform read and writes its own files, it will work fine.

The only problem you'll have is if you transfer a Windows-style data file to UNIX or vice versa. If that's the sort of thing you're doing, you can simply modify the string that you read in so that any \r character at the end is removed.

Note that won't adversely affect Windows-style files since, in memory, they don't have the \r - it's only put in the file when writing.

Upvotes: 1

Related Questions