0

I need to write text data to a memory-mapped file (using Boost). I have to do it in a raw mode, so I can't use boost::stream wrapper.

I want to write newline symbols in the text too. Obviously, I can't use text mode to rely on system \n conversion. I have to detect the correct \n representation on the given platform and write this sequence by myself.

The only way I could think of is to create a temp file, output \n to it in text mode and then reopen in a binary mode. But this approach is lame.

There is some API to directly query platform-dependent newline, isn't it?

Viacheslav Kroilov
  • 1,561
  • 1
  • 12
  • 23
  • 1
    How is your question related to mamory mapped files? You simple want to know if there is a standard method to query if lines of text files are terminated by "\r\n" or by "\n". – Jabberwocky Oct 22 '18 at 09:25
  • Also, you can output newlines in binary mode, no need to switch to text mode. – Shloim Oct 22 '18 at 09:26
  • The only system that uses "\r\n" as line ending is Windows. So you actually don't need to query at run time but you can do it at compile time using for example `#ifdef _WIN32`. Your compiled binary will either be compiled for Windows or for (e.g.) Linux, but you never will have an executable that runs on boths Windows and Linux. – Jabberwocky Oct 22 '18 at 09:36
  • @Jabberwoky It isn't, but to be fair, if the author had not mentioned that, you would have said "just open the file in text mode", and probably gone find a duplicate. – Gem Taylor Oct 22 '18 at 13:41
  • @Jabberwoky yes, that was the point as Gem Taylor said. – Viacheslav Kroilov Oct 23 '18 at 17:09

1 Answers1

2

No real need to do anything fancy, the following will work for Windows, Mac, and Linux:

#ifdef _WIN32
const std::string newline = "\r\n";
#else
const std::string newline = "\n";
#endif

Alternatively just write \n everywhere, most Windows editors (apart from Notepad and even that's changing) can handle Unix line endings.

Alan Birtles
  • 32,622
  • 4
  • 31
  • 60
  • Ok, I thought that there would be some more "bulletproof" method. I believe, this one may have problems on Cygwin, as it tries to emulate a complete Linux environment. But I'm sticking to this option anyway. Thank you – Viacheslav Kroilov Oct 23 '18 at 17:11