C++ ifstream::read 混乱

C++ ifstream::read confusion

我想遍历文件流的字节。 我正在使用 ifstream class。当您使用 read 函数时,它将字符从流复制到我在参数列表中指定的数组中。我有 3 个问题。

int length = 1024;
char buff[1024];
ifstream inf(fp, ios::in | ios::binary);
inf.read(buff, length);

之所以不用在"buff"前面加“&”是因为第一个参数不是指针而是引用?

如果我有这个怎么办:

int length = 1024;
vector<char> buffer;
ifstream inf(fp, ios::in | ios::binary);
inf.read(&buff[0], length);

它实际上做的是获取向量第一个元素的内存地址。 只有第一个地址! 但它仍然可以访问整个数组,因为它将字符复制到其中。这怎么可能? 同样的事情也适用于以下吗?:

int length = 1024;
char* buffer[1024];
ifstream inf(fp, ios::in | ios::binary);
inf.read(&buff[0], length);

这里,如何访问数组元素?

成员函数read声明如下

basic_istream<charT, traits>& read(char_type* s, streamsize n);

它的第一个参数是指针类型。

在本次通话中

inf.read(buff, length);

数组 buff 被编译器隐式转换为指向其第一个元素的指针。

所以这个调用等同于调用

inf.read( &buff[0], length);

但最后一个需要更多的输入。

如果你会写

inf.read(&buff, length);

那么参数的类型就是char ( * )[1024],编译器会报错,因为参数的类型和参数的类型不一样

关于使用向量而不是字符数组时的这段代码。

int length = 1024;
vector<char> buffer;
ifstream inf(fp, ios::in | ios::binary);
inf.read(&buff[0], length);

那么它是无效的,因为向量是空的。

你应该改写

int length = 1024;
vector<char> buffer( length );
ifstream inf(fp, ios::in | ios::binary);
inf.read(&buff[0], length);

What it actually does is that it takes the memory address of the first element of the vector. Only the address of the first! But it still has access to the whole array because it copies the characters into it. How is it possible?

函数的第二个参数指定第一个参数设置的内存地址如何变大。

函数可以声明为模板函数

template <size_t N>
basic_istream<charT, traits>& read( char_type ( &s )[N] );

但在这种情况下,您将无法将指针传递给动态分配的数组或数组的一部分。

向量和数组将它们的数据保存在连续内存中,所以第二个元素紧跟在第一个元素之后等等等等。所以访问整个array/vector 是指向第一个元素的指针和 array/vector.

的长度

顺便说一句,这段代码是错误的

int length = 1024;
vector<char> buff;
ifstream inf(fp, ios::in | ios::binary);
inf.read(&buff[0], length);

因为向量 buff 的大小为零,所以没有空间来读取数据。如果你这样写就好了

int length = 1024;
vector<char> buff(length);
ifstream inf(fp, ios::in | ios::binary);
inf.read(&buff[0], length);

还是这样更好(因为我们用size方法查询向量,看它有多大)

int length = 1024;
vector<char> buff(length);
ifstream inf(fp, ios::in | ios::binary);
inf.read(&buff[0], buff.size());

或者像这样更好(因为我们使用自描述的 data 方法来获取指向向量数据的指针)。

int length = 1024;
vector<char> buff(length);
ifstream inf(fp, ios::in | ios::binary);
inf.read(buff.data(), buff.size());