我不确定我是否正确这样做,所以我想查看我的代码.它有效,但我不确定它的工作正常.我需要它来读取二进制文件,并将16位整数存储在所需的确切大小的整数数组中.我试图这样做sizeof(storage[i])
,我可以看到我是否存储16位,但它说32(我猜是因为int自动分配4个字节?
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编辑:::::::::::::::::::::::::::::::::::::::::::::;
我将read语句更改为:
inputFile.read((char*)&storage[test], sizeof(2));和要键入的数组
short
.现在它很好用,除了输出有点奇怪:In File: data02b.bin 8 Currently at position4 Currently at position8 10000 10002 10003 0我不确定.bin文件中有什么,但我猜0应该不存在.大声笑