简体   繁体   English

在C ++中,seekg似乎包含cr字符,但read()删除了它们

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

I'm currently trying to read the contents of a file into a char array. 我目前正在尝试将文件的内容读取到char数组中。

For instance, I have the following text in a char array. 例如,我在char数组中有以下文本。 42 bytes: 42个字节:

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

This file is created in windows, and I'm using Visual Studio c++, so there is no OS compatibility issues. 此文件是在Windows中创建的,并且我使用的是Visual Studio c ++,因此没有操作系统兼容性问题。

However, executing the following code, at the completion of the for loop, I get Index: 39, with no 13 displayed prior to the 10's. 但是,执行以下代码,在for循环完成时,我得到索引: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;

However, when attempting to create a char array the length of the file, reading the file size as per below results in the 3 additional CR chars attributing to the total filesize so that length is equal 42, which is adding screwing up the end of the array with dodgy bytes. 但是,当尝试创建文件长度的char数组时,按以下方式读取文件大小会导致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] = '\0';
// Close the stream
fs.close();

Using a hex viewer, I have confirmed that file does indeed contain the CRLF (13 10) bytes in the file. 使用十六进制查看器,我已经确认该文件确实在文件中包含CRLF(13 10)字节。

There seems to be a disparity with getting the end of the file, and what the get() and read() methods actually return. 获取文件的末尾以及get()和read()方法实际返回的内容似乎存在差异。

Could anyone please help with this? 有人可以帮忙吗?

Cheers, Justin 干杯,贾斯汀

You should open your file in binary mode. 您应该以二进制模式打开文件。 This will stop read dropping CR. 这将停止读取丢弃的CR。

fs.open("task.txt", ifstream::in|ifstream::binary);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM