You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Windows下使用C++ std::fstream写入Unix风格换行符文件的方法

在Windows下用std::fstream写入Unix风格换行符的方法

你可以通过以下两种方式解决Windows下std::fstream自动转换换行符的问题,生成符合Unix规范的LF换行文件:

1. 以二进制模式打开文件

Windows下的std::fstream默认使用文本模式,会自动将代码中的\n转换为CR LF(\r\n)。切换到二进制模式后,所有字符都会被原样写入,不会进行换行符转换,这是最稳妥的方案。

代码示例:

#include <fstream>
#include <string>

int main() {
    // 打开文件时添加std::ios::binary标记
    std::ofstream output_file("unix_format.txt", std::ios::out | std::ios::binary);
    
    if (output_file.is_open()) {
        // 直接使用'\n'插入LF换行,不要用std::endl
        output_file << "Linux程序可识别的第一行内容\n";
        output_file << "第二行内容\n";
        output_file.close();
    }
    return 0;
}

注意:不要使用std::endl,因为它在任何模式下都会插入\n并刷新缓冲区,且在文本模式下仍会触发CR LF转换;二进制模式下虽然std::endl的\n不会被转换,但为了统一习惯,建议直接用'\n'或字符串中的\n。

2. 手动控制换行符输出(不推荐)

如果因为某些原因必须使用文本模式,可以直接写入'\n',但这种方式不如二进制模式可靠——文本模式的转换规则由系统决定,仍存在意外转换的风险。

代码示例:

#include <fstream>

int main() {
    std::ofstream output_file("unix_format.txt");
    if (output_file.is_open()) {
        // 直接输出字符'\n',避免依赖文本模式的自动转换
        output_file << "内容行1" << '\n';
        output_file << "内容行2" << '\n';
        output_file.close();
    }
    return 0;
}

额外注意事项

如果需要读取现有文件再重新写入,读取时也必须使用二进制模式(std::ios::in | std::ios::binary),避免读取过程中Windows将CR LF转换为\n,导致写入时再次转换出现重复问题。

内容的提问来源于stack exchange,提问作者anupurba mitra

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.13 19:14:57