简体   繁体   中英

C++: Not actually reading from binary file

I know this kind of question has been frequently asked but no matter what example I follow I can't seem to get the expected results. I want to read integers from a binary file and store them in a vector. I have the code below.

std::ifstream infile;
infile.open(fileName.c_str(), std::ios_base::binary | std::ios_base::in);

infile.seekg(0, infile.end);
long size = infile.tellg();

std::vector<int> input(size/sizeof(int), 0);

// Option 1
infile.read(reinterpret_cast<char*>(&input[0]), size);

// Option 2
infile.read((char*)&input[0], size);

infile.close();

I have tried both options when reading, but when I'm printing the contents of the vector, all elements are zero.

// Option 1
infile.read(reinterpret_cast<char*>(&input[0]), sizeof(int);

std::istream::read()
std::istream::tellg()

You need to pass the size of the piece of data you want to read, not the size of the entire file. As mentioned in the comments, you also need to reset the pointer to the beginning of the file after you determine the size.

If you're using a newer C++ (C++11), the conversion of the filename to a C-string is not necessary. If you have C++17, it may be worth learning the <filesystem> library.

If you're wanting to read many ints, put the read in a loop.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM