Linux系统下用C++读取含\r\n结尾的Windows文件问题求助
Linux下C++读取Windows格式文件并保留原换行符的解决方法
在Linux环境中,你的代码无法保留Windows文件的\r\n换行符,原因有两点:
- 默认以文本模式打开文件时,Linux下的C++标准库会自动将
\r\n转换为\n; getline()函数会读取到换行符为止,并直接丢弃换行符本身,导致原文件的换行标记完全丢失。
方法一:二进制模式打开,手动处理行分割
通过二进制模式打开文件,避免系统自动转换换行符,自行识别\r\n作为行结束标记,可完全保留原文件所有字符:
#include <fstream> #include <string> #include <iostream> using namespace std; int main() { string line_buffer; // 以二进制模式打开文件,禁用换行符自动转换 ifstream input_file("abcd.txt", ios::binary); char ch; while (input_file.get(ch)) { line_buffer += ch; // 检测Windows换行符\r\n if (ch == '\n' && line_buffer.size() >= 2 && line_buffer[line_buffer.size() - 2] == '\r') { // 输出完整行(包含原\r\n) cout << line_buffer; line_buffer.clear(); } } // 处理文件末尾无换行符的剩余内容 if (!line_buffer.empty()) { cout << line_buffer; } input_file.close(); return 0; }
方法二:文本模式下手动补充换行符(仅适用于纯Windows格式文件)
如果确定文件所有行都是\r\n结尾,可以在文本模式读取后,手动添加\r\n输出:
#include <fstream> #include <string> #include <iostream> using namespace std; int main() { string myText; ifstream MyReadFile("abcd.txt"); while (getline(MyReadFile, myText)) { // 输出原内容+Windows换行符 cout << myText << "\r\n"; } MyReadFile.close(); return 0; }
注意:这种方法仅适用于文件所有行都是Windows格式换行的场景,如果存在混合换行(部分行是
\n),会导致多余的\r出现。
内容的提问来源于stack exchange,提问作者abbas ravat
相关产品推荐
相关产品推荐

