在c++中,seekg似乎包含cr个字符,但是read()去掉了它们

In c++ seekg seems to include cr chars, but read() drops them

本文关键字:read 但是 掉了 字符 seekg c++ cr 包含      更新时间:2023-10-16

我正在尝试将文件的内容读取到字符数组中。

例如,我在一个字符数组中有以下文本。42个字节:

{
    type: "Backup",
    name: "BackupJob"
}

这个文件是在windows中创建的,我使用的是Visual Studio c++,所以没有操作系统兼容性问题。

但是,执行以下代码,在for循环结束时,我得到Index: 39,在10之前没有显示13。

// Create the file stream and open the file for reading
ifstream fs;
fs.open("task.txt", ifstream::in);
int index = 0;
int ch = fs.get();
while (fs.good()) {
    cout << ch << endl;
    ch = fs.get();
    index++;
}
cout << "----------------------------";
cout << "Index: " << index << endl;
return;

然而,当尝试创建一个文件长度的字符数组时,按照下面的方式读取文件大小会导致3个额外的CR字符归为总文件大小,因此length等于42,这将用不安全的字节添加到数组的末尾。

// Create the file stream and open the file for reading
ifstream fs;
fs.seekg(0, std::ios::end);
length = fs.tellg();
fs.seekg(0, std::ios::beg);
// Create the buffer to read the file
char* buffer = new char[length];
fs.read(buffer, length);
buffer[length] = '';
// Close the stream
fs.close();

使用十六进制查看器,我已经确认文件中确实包含CRLF(13 10)字节。

获取文件的结尾和get()和read()方法实际返回的内容似乎存在差异。

有谁能帮帮忙吗?

欢呼,贾斯汀

您应该以二进制模式打开文件。这将停止读取丢弃CR

fs.open("task.txt", ifstream::in|ifstream::binary);
相关文章: