I'm trying to read binary of a file into a vector<char>
in c++ but reading function seems to behave like pass-by-value even though it is not.
Here is my simplified code:
#define sz 4096
int main(){
string filename="a/file/path";
vector<char> block_hex;
read_Xbytes(filename, 0, sz, block_hex);
cout << "\nnum bytes: " << block_hex.size() << " size: " << sz << endl;
}
void read_Xbytes(string fpath, int pos, int Xbytes, vector<char>& bytes) {
ifstream is;
is.open(fpath, ios::binary);
is.ignore(pos);
if (Xbytes > 0) {
bytes.reserve(Xbytes);
is.read((char*)&bytes[0], Xbytes);
}
is.close();
for (int i = 0; i < 16; i++)
cout << hex(bytes[i]) << " ";
cout << endl;
}
hex
function is printing the hex values of each byte. Inside the function, it works perfectly fine; I checked with HxD
, a hex editor, there is no problem. However, in main
it prints out num bytes: 0 size: 4096.
I tried to change the function to vector<char> read_Xbytes(string fpath, int pos, int Xbytes)
, still same result.
I'm wondering why the function behaves like pass-by-value? I couldn't really find anything useful.
I'm working on Windows 7 and Visual Studio 2015.