0

Please, help me. I can't read binary file. The file's length is 198944, but my code reads 374. I tried to use fread, ifstream, WinAPI ReadFile. This is the function that reads file:

std::string ReadThisFile(std::string aPath) {
   FILE *inputstream = fopen(aPath.c_str(),"rb");
   long size;
   size_t result; 
   fseek(inputstream,0,SEEK_END); 
   size = ftell(inputstream); 
   rewind(inputstream); 
   char *buff = new char [size];
   result = fread (buff,1,size,inputstream); 
   std::string ret=buff; 
   fclose(inputstream); 
   delete[]buff; 
   return ret; 
}

File sample

Any help is needed, thank you!

3
  • Are you using strlen to get the final size? You can't do store binary content in a string. Commented Feb 15, 2013 at 6:33
  • 1
    Is the file supposed to be an ASCII text file you want to load into a single std::string? If not, use a different container. (like a std::vector<unsigned char> or something similar). Commented Feb 15, 2013 at 6:42
  • Btw, fseek(binary_stream, offset, SEEK_END) is not guaranteed to work (according to the C standard from 1999). Commented Feb 15, 2013 at 7:15

3 Answers 3

1

As long as you're aware of that the std::string that you return contains binary data, replace

std::string ret=buff;

with

std::string ret(buff, size);
Sign up to request clarification or add additional context in comments.

Comments

0

You can't put binary data in a string. Remember that a string is terminated by the special character '\0' which is the same as the value zero. If the binary data contains a zero, that is the same as the end of the string.

You should probably use a std::vector<int8_t> to store binary data.

1 Comment

Thanks. Yes, that was my problem.
0

The problem is here:

std::string ret = buff;

According to this, it:

"Copies the null-terminated character sequence (C-string) pointed by s."

So it stops as soon as a 0x00 character is reached.

If you were to return buff (which is a dangerous practice) or have your function take a char array as an input parameter and merely store it there, it should work. And you may want to return a length indicator, since otherwise C++ will not know how large the array is.

1 Comment

Thanks. Yes, that was my problem.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.