Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
311 views
in Technique[技术] by (71.8m points)

c++ - Portable way to determine the platform's line separator

Different platforms use different line separator schemes (LF, CR-LF, CR, NEL, Unicode LINE SEPARATOR, etc.). C++ (and C) runtime libraries make a lot of this transparent to most programs, by converting ' ' to and from the target platform's native new line encoding. But if your program needs to determine the actual byte sequence used, how could you do it portably?

The best method I've come up with is:

  1. Write a temporary file in text mode with just ' ' in it, letting the run-time do the translation.
  2. Read back the temporary file in binary mode to see the actual bytes.

That feels kludgy. Is there a way to do it without temporary files? I tried stringstreams instead, but the run-time doesn't actually translate ' ' in that context (which makes sense). Does the run-time expose this information in some other way?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I'm no C/C++ expert, but there doesn't appear to be anything in the standard library that will directly give you the line separator. The translation is handled transparently by the text-mode file functions.

Even though you feel your approach is "kludgy", it is probably the simplest and most reliable, since you are really testing what line separator is used and written out. And is portable, since you are using standard library functions to write and read the file.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...