pokiman
pokiman

Reputation: 986

Reading an entire file in binary mode using C++

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);

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..?

Upvotes: 1

Views: 4101

Answers (6)

Sarfaraz Nawaz
Sarfaraz Nawaz

Reputation: 361722

In C++, you can use std::ifstream which comes with idiomatic reading style as:

std::ifstream file("file.bin", std::ifstream::binary); //binary mode!
std::istream_iterator<char> begin(file), end);  //setup iterators!
std::vector<char> v(begin,end);  //read all data into a vector!
//v contains the binary data, which you can use from now on

//you can get the pointer to the data as
char *buffer = &v[0];
size_t sizeOfBuffer = v.size();
//you can use buffer and sizeOfBuffer instead of v.

//just remember that the lifetime of buffer is tied with the lifetime of v
//which means, if v goes out scope, the pointer `buffer` will become invalid

Hope you read the comments in the above snippet. :-)

Upvotes: 0

Johan Lundberg
Johan Lundberg

Reputation: 27058

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

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

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)

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

Upvotes: 2

CHollman82
CHollman82

Reputation: 616

In your call to fread you are telling it to read 1 byte...

It should be: fread(stream, 1, filesize, fd);

Upvotes: 0

Chris Eberle
Chris Eberle

Reputation: 48795

From man 3p fread:

fread() and fwrite() return the number of items successfully read or written (i.e., not the number of characters). If an error occurs, or the end-of-file is reached, the return value is a short item count (or zero).

You told it to read 1 file-length, and that's what it read.

Upvotes: 1

frast
frast

Reputation: 2740

If you want the number of bytes read you need to switch the arguments like so:

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

Upvotes: 2

Useless
Useless

Reputation: 67812

RETURN VALUE
       fread() and fwrite() return the number of items  successfully  read  or
       written  (i.e.,  not the number of characters).  If an error occurs, or
       the end-of-file is reached, the return value is a short item count  (or
       zero).

You told it to read 1 item of size fileSize, and it did.

Upvotes: 1

Related Questions