istream::read未正确填充char数组
istream::read not filling char array correctly
我正在打开一个用于二进制读取的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
计算字节数,直到找到一个为零的字节。可能是数据并非都是可打印的字符吗?
您的二进制字符串中可能存在EOF
或NULL
等效项,导致strlen
出现问题。
相关文章:
- 为什么我的 Char* 在填充整数后为空?
- 无法获取已填充堆栈<char>的顶部元素
- 用 int 值填充 char 数组
- C++用用户输入在循环中填充 char 数组:输入整个字符串时到底发生了什么?
- 缓冲区用不需要的数据填充 char 数组中的最后一个空格
- 如何填充项目为 8 个字符的集合?(std::set<char [8]>)
- 如何创建 std::vector of char/std::byte,其中第一个字节对齐到 16 个字节,但没有填充
- 在函数内部填充和比较char*
- 如果我有一个固定大小的填充ascii数字的char数组,我知道它指的是一个无符号整数,那么将其转换为无符号整数的最快方法
- 如何在 c++ 中填充指针数组,类型 char
- 正在检查未完全填充的数组中的char out是否为空
- istream::read未正确填充char数组
- Python使用ctypes传递char *数组并填充结果
- 如何使用 boost.python 将预填充的"unsigned char*"缓冲区传递给C++方法?
- 填充标准::矢量缓冲区的最佳方法<char>
- 填充Unsigned Char数组
- 用const char*填充wstring的最佳方式
- 如何从c++返回char **并在Python中使用ctypes将其填充到列表中
- 在char数组中填充空格
- 如何用JNIjobjectarray(JavaString[])填充C++char[]