c++ - ifstream::read keeps returning incorrect value -


i working way through teaching myself how work files in c++, , having bit of difficulty extracting binary information files.

my code:

std::string targetfile = "simplehashingfile.txt"; const char* filename = targetfile.c_str(); std::ifstream file;  file.open( filename, std::ios::binary | std::ios::in ); file.seekg(0, std::ios::end);  //  go end of file std::streamsize size = file.tellg();  //  size of file  std::vector<char> buffer(size);  //  create vector of file size bytes  file.read(buffer.data(), size);  //  read file buffer vector int totalread = file.gcount();  //  check data read std::cout<<"total read: " << totalread << std::endl;   //  check buffer:   std::cout<<"from buffer vector: "<<std::endl; (int i=0; i<size; i++){     std::cout << buffer[i] << std::endl; } std::cout<<"\n\n"; 

the "simplehashingfile.txt" file contains 50 bytes of normal text. size correctly determined 50 bytes, gcount returns 0 chars read, , buffer output (understandably gcount) 50 line list of nothing.

for life of me cannot figure out went wrong! made test code earlier:

//  writing binary file std::ofstream ofile; ofile.open("testbinary", std::ios::out | std::ios::binary);  uint32_t bytes4 = 0x7fffffff;  //  max 32-bit value uint32_t bytes8 = 0x12345678;  //  32-bit value   ofile.write( (char*)&bytes4 , 4 ); ofile.write( (char*)&bytes8, 4 );  ofile.close();    //  reading file std::ifstream ifile; ifile.open("testbinary", std::ios::out | std::ios::binary);  uint32_t reading;  //  variable read data  uint32_t reading2;  ifile.read( (char*)&reading, 4 ); ifile.read( (char*)&reading2, 4 );  std::cout << "the file contains:  " << std::hex << reading << std::endl; std::cout<<"next 4 bytes:  "<< std::hex << reading2 << std::endl; 

and test code wrote , read perfectly. idea doing wrong? thank can point me in right direction!

you never reset file beginning when read it

std::streamsize size = file.tellg(); //<- goes end of file std::vector<char> buffer(size);  //  create vector of file size bytes  file.read(buffer.data(), size);  //<- read end of file read nothing int totalread = file.gcount(); 

you need call seekg() again , reset file pointer beginning. use

fille.seekg(0, std::ios::beg); 

before

file.read(buffer.data(), size); 

Comments

Popular posts from this blog

python - pip install -U PySide error -

arrays - C++ error: a brace-enclosed initializer is not allowed here before ‘{’ token -

cytoscape.js - How to add nodes to Dagre layout with Cytoscape -