【发布时间】:2016-06-21 17:15:56
【问题描述】:
#include <iostream>
#include <cmath>
#include <fstream>
#include <cstring>
#include <string>
using namespace std;
int main()
{
int numcount; //amount of numbers
int numb; //temporary number for writing reaction
fstream fbin ("filename.bin", ios::binary | ios::out);
if (!fbin){
cout << "err";
return -1;
}
char thing[6]; //reading of Done!
cout << "Starting Write Sequence...\n";
cout << "How many numbers do you want to write?\n";
cin >> numcount;
cout << "Okay, " << numcount << " numbers.\n";
fbin.write((char*)(&numcount), 4); //writes amount of numbers to first
for(int i = 0; i < numcount; i++){ //loop that writes numcount numbers to file
cout << "Enter number " << i + 1 << ": ";
cin >> numb;
cout << "Number " << numb << " entered. Writing...\n";
fbin.write((char*)(&numb), 4);
}
fbin.write("Done!", sizeof("Done!") - 1);
fbin.seekp(numcount * 4 + 4); //Finds position of Done!. numcount * 4 because normal integers are 4 bytes,
//and + 4 because I also need to include numcount in the file, so it can be read.
fbin.read(thing, 5);
cout << thing << "\n";
cout << "\"Done!\" should have appeared before this!";
}
这段代码的最后一部分应该打印出来
Done!
到控制台,而是打印@。
这是二进制文件中包含 4 个数字(7、5、8、7)的内容:
04 00 00 00 07 00 00 00 05 00 00 00 08 00 00 00 07 00 00 00 44 6F 6E 65 21
....................Done!
编辑:意外删除 fbin.read(thing, 5);仍然做同样的事情
【问题讨论】:
-
你从哪里读过代码中的
thing缓冲区?? -
看起来像是错字。
fbin.seekp应该是fbin.seekg因为你想推进 get 指针而不是 put 指针 -
@NathanOliver 仍然做同样的事情(@ 符号)
-
@LightnessRacesinOrbit 我该如何解决这个问题?
-
@LightnessRacesinOrbit 我正在尝试将
Done!从 filename.bin 读取到控制台,作为字符串thing