在c++中,seekg似乎包含cr个字符,但是read()去掉了它们
In c++ seekg seems to include cr chars, but read() drops them
我正在尝试将文件的内容读取到字符数组中。
例如,我在一个字符数组中有以下文本。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);
相关文章:
- std::map<struct,struct>::find 找不到匹配项,但是如果我循环通过 begin() 到 end(),我在那里看到匹配项
- 当我在第一个循环中使用"auto"时,它工作正常,但是使用"int"它会给出错误,为什么?
- 代码在我的计算机上运行良好,但是在将其提交给coursera时遇到未知的信号11问题
- 使用 ImageIO.read() 生成的图像是否仍然使用传递给它的相同内存?
- std::ifstream::read 不会读取所有 512 字节,并设置 EOF 和失败位
- 我有三个 getline,但是一旦编译,输入就太多了
- 我要求用户输入大小和数组,但是当我打印矢量时,它仅显示'0'作为输出
- write() 和 read() 中几乎没有混淆
- C++ TCP 套接字通信 - 连接按预期工作,几秒钟后失败,没有收到新数据,read() 和 recv() 块
- 为什么调试器引发"read access violation. this was nullptr"异常?
- 对同一文件使用 .read 的次数是否有限制?
- Win32 API - HWND "{unused = ???} Unable to read memory"错误
- 我在 C++ 中创建了一个函数来递归反转字符串,但是之后如何使功能打印一个 endl?
- 为什么我会"Invalid read of size 8"?(瓦尔格林德)
- QDataStream read to QVector
- asio::read() 需要很长时间,使用 asio::write 没有问题
- Read OpenCV Mat 16bit to QImage 8bit Greyscale
- 如果 I/O read() 处于阻塞阶段,如何使用 Ctrl+C 退出 C++ 程序?
- 如果我们在其中输入一个整数,则字符会给出整数作为输出,但是当分配给它一个整数时,这不会发生。为什么?
- 在c++中,seekg似乎包含cr个字符,但是read()去掉了它们