【发布时间】:2025-11-25 21:15:01
【问题描述】:
当我尝试操作文本文件时,我希望将行尾字符设置为目标操作系统上的首选字符,例如 linux 文本文件中的 LF 和 windows 文本文件中的 CRLF。
相关问题
根据问题C++: Is there a standard definition for end-of-line in a multi-line string constant?,eol 字符取决于源文件中的字符。这意味着,当我使用
std::ofstream out{"hello.txt"};
out << R"(Hello
World)" << std::endl;
“hello.txt”中的 eol 字符映射到单个 '\n' 字符,即使源文件以 Windows 文本格式存储。
根据问题Detect Windows or Linux in C, C++和Standard #ifdef for Cygwin,我可以用
#if defined(_WIN32) || defined(__CYGWIN__)
#define END_OF_LINE "\n\r"
#else
#define END_OF_LINE "\n"
但是,我不知道如何将这些代码放入之前的代码段中。
Java 解决方案
在java中,使用
System.getProperty("line.separator");
将返回相应的行尾字符。
JDK 7 将上述行替换为System.lineSeparator(),效率更高。
C++ 解决方案?
C++17 文件系统提供了一个常量:std::filesystem::path::preferred_separator 来告诉各种操作系统平台上的路径分隔符。我认为这是一个很好的形式。
在 C++17 或更新的标准中是否有任何现有的工具可以提供std::xxx::preferred_eol_separator 这样的便利?
【问题讨论】:
-
@Nicol Bolas 我犯了一个错误。改正后。谢谢。
标签: c++17