寻求不会到所需的位置

seekp not going to required position

本文关键字:位置      更新时间:2023-10-16

在这个程序中,我想更改文件中的一些值。现在我以追加模式打开文件并将我的 seekp 指针移动到我给定的位置。但问题是它在文件末尾写入数据,而不是在 seekp 指针所在的位置。

#include<iostream>
#include<fstream>
using namespace std;
int main(){
//creates a file for testing  purpose.  
    ofstream fout;
    fout.open("test.txt");
    fout<<1;
    fout<<" ";
    fout<<34;
    fout<<" ";
    fout<<-1;
    fout<<" ";
    fout<<-1;
    fout.close();
//reads the data in the file    
    ifstream fin;
    fin.open("test.txt");
    fin.seekg(0,ios::beg);
    fin.unsetf(ios::skipws);//for taking whitespaces
    char sp;
    int item;
    fin>>item;
    while(!fin.eof()){
    cout<<item<<endl;
    fin>>sp;//to store whitespaces so that fin can take next value
    fin>>item;  
    }
    cout<<item<<endl;
    fin.close();
//opening file for editing
    fout.open("test.txt",ios::app);
    fout.seekp(5,ios::beg);
    fout<<3;
    fout.close();
    return 0;
}
例如,

如果您阅读此参考,您会发现std::ios::app意味着

在每次写入之前查找到流的末尾

因此,无论您在哪里寻找,所有写入都将在文件末尾完成。

修改文件的最佳方法是将其读入内存,然后将其重写为临时文件,然后将临时文件移动到原始文件上。