istream::read未正确填充char数组

istream::read not filling char array correctly

本文关键字:填充 char 数组 read istream      更新时间:2023-10-16

我正在打开一个用于二进制读取的istream:

ifstream file;
file.open (this -> fileName.c_str(), ios::binary);

然后,当文件很好时,我尝试读取一个字符数组指针:

char data[numberOfBytes];
char * p = data;
file.read(p, numberOfBytes);
cout << "size: "   << sizeof(p)     << end
cout << "gcount: " << file.gcount() << endl;
cout << "strlen: " << strlen(p)     << endl;

以上每一项的输出都不同。Sizeof()生成4,这是字符指针的正确大小。gcount()生成numberOfBytes的任何值。但是,strlen()返回一些其他较小的数字。因此,尽管read()已经移动了istream指针numberOfBytes,但我在char数组中没有这些字节。我希望所有这些字节都在char数组中。我该如何做到这一点?发生了什么事?

如果您正在读取二进制数据,那么您可能正在读取值为零的字节,或者字符串术语中的null字符。

strlen()计算字符串大小的方法是从字符串的开头开始,然后计数,直到达到空字符。

因此,strlen()将只报告到null字符的字节数,而不是实际读取的字节数。

试试这个:

我只能猜测您还没有初始化numberOfBytes。我刚刚复制并打印,它对我有效:

//file test.C
#include <iostream>
#include <fstream>
#include <string>
#include <cstring>
using namespace std;
int main() {
    ifstream file;
    file.open ("test.C", ios::binary);
    char data[1024];
    char *p = data;
    file.read(p, 1024);
    cout << "size: "   << sizeof(p)     << endl;
    cout << "gcount: " << file.gcount() << endl;
    cout << "strlen: " << strlen(p)     << endl;
    cout << "data: " << p << endl;
    return 0;
}

strlen报告到第一个空字节为止的字节数,但不包括第一个零字节。

函数strlen计算字节数,直到找到一个为零的字节。可能是数据并非都是可打印的字符吗?

您的二进制字符串中可能存在EOFNULL等效项,导致strlen出现问题。