我有一個以二進制格式存儲ints的文件。我正在用C++編寫一個函數,它接受int數據並將其插入到文件中的特定位置。將數據插入文件中的特定位置而不覆蓋在C++中
void AddData(int position, int data);
- 位置是數據必須插入的索引。
- 數據是要插入的整型值。
代碼
void AddData(int position, int data)
{
fstream os;
char buff[4096];
cnt1 = position;
cnt2+=(data_cnt-cnt1); // data_cnt is global var to cout the no. of data items
os.open("edata.dat", ios::out | ios::in | ios::binary);
os.seekg(0); // start from beg
os.seekg(cnt1*sizeof(int)); // move to position at which data has to be inserted
os.read(reinterpret_cast<char*>(buff), cnt2*sizeof(int)); // read rest of file
os.seekg(cnt1*sizeof(int)); // move back to previous position
cout << os.tellg();
os.write(reinterpret_cast<char*>(&data), sizeof(int)); //add data
os.write(reinterpret_cast<char*>(buff), cnt2*sizeof(int)); //write back the read data
data_cnt++;
}
當函數被調用一次,它顯示數據項被添加兩次。當第二次調用函數時,tellg()顯示-1。
搞不清楚,怎麼回事?