1

このプログラムでは、ファイルの値を変更したいと考えています。ファイルを追加モードで開き、シーク ポインターを指定された場所に移動しています。シークポインタがあります。

#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;
}
4

1 に答える 1

2

たとえば、このリファレンスstd::ios::appを読むと、それが意味することがわかります

各書き込みの前にストリームの最後までシークする

したがって、どこを探しても問題ありません。すべての書き込みはファイルの最後で行われます。

ファイルを変更する最善の方法は、ファイルをメモリに読み込み、一時ファイルに書き直してから、一時ファイルを元のファイルに移動することです。

于 2013-09-14T20:09:13.407 に答える