|
发表于 2022-7-28 14:08:58
|
显示全部楼层
本帖最后由 yoobaby 于 2022-7-28 14:56 编辑
看注释,解释并不是很严谨,但基本意思差不多。
- ofstream ofs;
- ofs.open("T:\\fs.txt");
- if (!ofs) return 0;
- int iOut = 9000;
- ofs << iOut << endl;
- ofs << iOut + 1 << endl;
-
- iOut = 3000;
- ofs.write((const char*)&iOut, sizeof(iOut));
- ofs.close();
- ifstream ifs;
- ifs.open("T:\\fs.txt");
- if (!ifs) return 0;
- int iIn = 0;
- ifs >> iIn;
- cout << ifs.tellg() << endl;
- cout << "var22 first " << iIn << endl;
- ifs >> iIn;
- cout << ifs.tellg() << endl;
- cout << "var22 second " << iIn << endl;
- iIn = 0;
- cout << ifs.tellg() << endl;
- /*
- * 第一次 >> tellg() 位置到第4字节,
- * 第二次 >> 会跳过第一行的换行符endl (/r/n) 两个字节,从读6个字节读取4个字节;此时teelg() 位置是10
- * 注:/t 空格 之类的空白符好像也会跳过,自行测试;没去深究!
- * read时,读取是从10开始读的,会读取/r/n;所以跳过2个字节。再读才会是正确的!
- * 你也可以 ofs << iOut + 1 << endl; 这边不要<<endl,就不需要跳过了!
- */
- ifs.seekg(2, ifs.cur);
-
- ifs.read((char*)&iIn, sizeof(iIn));
- cout << ifs.tellg() << endl;
- cout << "var22 third " << iIn << endl;
- ifs.close();
复制代码 |
|