问题
I'm not sure if I'm doing this right so I want to check my code. it works but I'm not sure its working right. I need it to read the binary file, and store the 16 bit integers in an array of ints that is the exact size needed. I tried to do sizeof(storage[i])
so I could see if I was storing 16 bits but it says 32 (I'm guessing because int automatically allocates 4 bytes?
void q1run(question q){
int end;
std::string input = q.programInput;
std::ifstream inputFile (input.c_str(), ios::in | ios::binary); //Open File
if(inputFile.good()){ //Make sure file is open before trying to work with it
//Begin Working with information
cout << "In File: \t" << input << endl;
inputFile.seekg(0,ios::end);
end=inputFile.tellg();
int numberOfInts=end/2;
int storage[numberOfInts];
inputFile.clear();
inputFile.seekg(0);
int test = 0;
while(inputFile.tellg()!=end){
inputFile.read((char*)&storage[test], sizeof(2));
cout << "Currently at position" << inputFile.tellg() << endl;
test++;
}
for(int i=0;i<numberOfInts;i++){
cout << storage[i] << endl;
}
}else{
cout << "Could not open file!!!" << endl;
}
}
EDIT:::::::::::::::::::::::::::::::::::::::::::::;
I changed the read statement to:
inputFile.read((char*)&storage[test], sizeof(2));
and the array to type short
. now Its pretty well working except the output is a little strange:
In File: data02b.bin
8
Currently at position4
Currently at position8
10000
10002
10003
0
I'm not sure what's in the .bin file, but I'm guessing the 0 shouldn't be there. lol
回答1:
Yes, int is 4 bytes (on 32-bit x86 platform).
You have two problems:
- As Alec Teal correctly mentioned in comment, you have your storage declared as int, which means 4 bytes. Not a problem, really - your data will fit.
- Actual problem: your line which is reading the file:
inputFile.read((char*)&storage[test], sizeof(2));
is actually reading 4 bytes, because 2 is integer, sosizeof(2)
is 4. You don't needsizeof
there.
回答2:
Use: int16_t
in <cstdint>
. (guaranteed 16bits)
Short
s and int
s can be of various sizes depending on the architecture.
回答3:
Storage is declared as an 'array' of "int"s, sizeof(int)=4
This shouldn't be a problem though, you can fit 16 bit values in 32 bit spaces, you probably meant short storage[...
Additionally for the sake of full-disclosure, sizes are defined in terms of sizeof(char) as a monotonically increasing sequence.
4 is by far the most common though, hence the assumption. (Limits.h will clarify)
回答4:
One way to store 16 bits integers is to use the type short
or unsigned short
.
You used sizeof(2)
which is equal to 4 because 2 is of type int
so the the way to read 16 is to make storage
of type short
and the read:
short storage[numberOfInts];
....
inputFile.read((char*)&storage[test], sizeof(short));
You can find here a table containing the sizes of all the types.
来源:https://stackoverflow.com/questions/20526734/reading-16-bit-integers-from-binary-file-c