Umer Farooq
Umer Farooq

Reputation: 7486

Binary files in C++

I want to store data from desired byte upto another desired byte of the file opened in binary mode in to another file. Lets say file pointer is at byte# 10, now i want to read data from byte # 11 to byte # 30. I know i have to use fread() function but don't know how to tell this function to read from desired location upto another desired location. I am a beginner so bear answering this question.

I know fread() is C function, I want C++ equivalent functions for doing this work. A link or suggestion of book for learning file handling will be great!

Thanks alot for your help!

Upvotes: 1

Views: 892

Answers (2)

marinus
marinus

Reputation: 936

Well, the prototype for fread is :

size_t fread ( void * ptr, size_t size, size_t count, FILE * stream );

And fseek is:

int fseek ( FILE * stream, long int offset, int origin );

If you want to get to byte #11, you can do:

fseek(file, 11, SEEK_SET) // this means: go 11 bytes from the start position.

or, since you're already at byte 10, you can do:

fseek(file, 1, SEEK_CUR)  // this means: go 1 byte beyond current position.

Then, to read up to byte 30 from byte 11, you need to read 19 bytes (30 - 11), so you do:

fread(buffer, sizeof(char), 19, file).

Upvotes: 1

Kerrek SB
Kerrek SB

Reputation: 477040

You have to seek:

std::ifstream infile("source.bin", std::ios::binary);

infile.seekg(10, std::ios::beg);  // seek to 10 bytes from the beginning

char buf[20];

if (!infile.read(buf, 20)) { /* error */ }

// now your data is in buf

The stdio interface is is similar, but since this is C++, we prefer the iostreams one. You must never, ever use I/O operations without checking their return value, and in iostreams this is fairly easy. With fread you have to be careful to interpret the return value correctly.

Upvotes: 3

Related Questions