本文介绍了使用C ++以二进制模式读取整个文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用visual c ++以二进制模式读取整个jpg文件。代码如下:

I am trying to read an entire jpg file in binary mode using visual c++. The code is as follows:

FILE *fd = fopen("c:\\Temp\\img.jpg", "rb");
if(fd == NULL) {
    cerr << "Error opening file\n";
    return;
}

fseek(fd, 0, SEEK_END);
long fileSize = ftell(fd);
int *stream = (int *)malloc(fileSize);
cout << fileSize << '\n';
fseek(fd, 0, SEEK_SET);
int bytes_read = fread(stream, fileSize, 1, fd);
printf("%i\n", bytes_read);
fclose(fd);

问题是 bytes_read 1. fileSize 变量包含正确的文件大小。所以我不知道为什么 bytes_read 总是1,不等于fileSize ..

The problem is that the bytes_read is always 1. The fileSize variable contains the correct size of the file. So I am not sure why the bytes_read is always 1 and not equal to fileSize..?

推荐答案

int n_read = fread(stream, fileSize, 1, fd);

返回您获得的大小fileSize的块数。在这种情况下1。

returns the number of chunks of size fileSize you got. In this case 1.

查看C标准的第7.21.8.1节:
http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1548.pdf

Look at section 7.21.8.1 of the C standard:http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1548.pdf (page 334)

因此,您需要将 n_read 乘以 fileSize 获取读取的字节数。

So you need to multiply n_read with fileSize to get the number of bytes read.

这篇关于使用C ++以二进制模式读取整个文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-19 21:19