How to read unsigned short from file?

I have a bitmap that I am processing and I need to open the file and keep the first unsigned short.

I tried to accomplish this with FILE and fscanf (), but fscanf () always fails and returns 0 (number of items successfully read).

FILE *pFile = fopen ( fileName->c_str() , "r" ); if ( pFile == NULL ) { cerr << "couldn't open file ; exiting..." << endl; exit(0); } unsigned short seed; fscanf (pFile, "%hu", &seed); 

Does anyone know of a different approach that I could take (maybe in that case?) Or maybe just give me some pointers? Any help would be greatly appreciated.

Thanks.

+4
source share
3 answers

Do not use formatted functions such as * scanf; they expect character representations of data, the addition of * printf functions that translate values ​​into representations of characters.

 unsigned val; f = fopen (filename, "rb"); if (fread (&val, 1, sizeof (val), f) != sizeof (val)) // error 

The biggest caveat is how the file was written. If the author’s continent is different from the computer on which it is running, then an explicit user code should be used instead:

 unsigned val; unsigned char buf[2]; f = fopen (filename, "rb"); if (fread (buf, 1, sizeof (buf), f) != sizeof (buf)) // error else { // val = (buf [0] << 8) | buf [1]; // for big endian written file val = (buf [1] << 8) | buf [0]; // for little endian written file } 
+12
source

Ahhh! Not! fscanf for text! %hu will look for strings like "1234" in the file, not the actual bytes!

Use fread.

eg.

 FILE *fp = fopen("foo", "rb"); unsigned short x; fread(&x, sizeof x, 1, fp); 

In fact, follow the content and open the file in binary format. "rb" for security on Windows. Check return codes, etc.

+3
source
 std::ifstream input("inputfile.txt"); unsigned short value; input >> value; 
+1
source

All Articles