I have declared a variable “data” with type “unsigned short”, and I wrote it to a file use fprintf. I tried to read the data out using fscanf in another method, but the number did not come out right.
Could anyone tell me what the correct data type I should use when I do
fscanf("%?", &data)? (I tried to use %u and %d, but none of them give the right number. I’ve also checked the file, and the number in the file seems correct. )
This is probably going to go under the pedantic column, but unsigned shorts are to be formatted by %hu, signed shorts by %hd, with unsigned char being %hhu.
The reason why using the format %d for short and char works is the compiler will generally keep variables word (32bit) aligned on the stack, with the other part of the data zero’d off. This of course depends on the optmization. If you where to optmize for memory, your code may stop working. If you are using packed data, then you will of course be displaying 2 shorts put together (and that just sounds bad doesn’t it )
If you add -w9, gcc will warn you about impropper format strings.
[thomas@loman test]$ cc -o fmt -Wall fmt.cc
fmt.cc: In function `int main()':
fmt.cc:10: warning: int format, different type arg (arg 2)
[thomas@loman test]$ ./fmt
data 3: 8
data 2: 7
data 1: 6
data 0: 5
5
0
0
0
data 3: 8
data 2: 7
data 1: 6
data 0: 5
5
6
7
8
Notice how the most short of the int over wrote the next element in the array, but when you give scanf the apropriate format the array contains what you would expect.
It is scary to go through code that works despite the best efforts of the author. BTW, yeah, the example was done on my Linux box, my nto box has temporarily donated it power supply to another box, but I would suspect QNX did not make that many mods to gcc???