以下小程序应该创建一个二进制文件,写入6 uint(typedef' ed as unsigned int),然后从同一个文件中读取并打印数据。
#include <iostream>
#include <fstream>
#include <string>
typedef unsigned int uint;
using namespace std;
int main(int argc, char* argv[])
{
string usr = [my username];
string szFile = "C:/Users/" + usr + "/iotest.bin";
cout << "File Streaming Test\n" << sizeof(uint) << "\n\n";
ifstream inFile = ifstream(szFile, ios_base::in | ios_base::binary);
if (inFile.fail()) {
// file probably DNE, create it and write some data to it
inFile.clear();
// first, close the input stream
// so the output stream can be opened
inFile.close();
// open the output stream
ofstream outFile = ofstream(szFile, ios_base::out | ios_base::trunc | ios_base::binary);
// make sure these are written as uint
uint zero = 0;
uint one = 1;
uint two = 2;
// write the data
outFile << two << two << zero << one << one << zero;
// flush and close the output stream
outFile.flush();
outFile.close();
}
// if we had to create the file,
// then reopen the input stream
if (!inFile.is_open())
inFile.open(szFile, ios_base::in | ios_base::binary);
// read 6 uint from the file
uint arr[6];
for (int i = 0; i < 6; i++) {
inFile >> arr[i];
cout << arr[i] << endl;
}
// pause
while (cin.get() != '\n');
// inFile auto-closes when it goes out of scope
return 0;
}
当我运行程序一次时,它会生成以下输出:
File Streaming Test
4
220110
3435973836
3435973836
3435973836
3435973836
3435973836
第二次运行程序(检查文件浏览器中确实存在该文件后)会生成相同的输出。
Windows(文件浏览器)表示创建的文件大小只有6个字节,大小应该是6 * 4 = 24个字节。它就像outFile只是写了我给它的一部分。在一个uint中读取220110
是奇怪的,因为它匹配我写的六个数字,但二进制表示不会像这样连接数字。