overwriting some text in a file using fstream and delete the rest of the file

人走茶凉 提交于 2019-12-10 18:14:14

问题


I am trying to write a program that read a file using fstream then, rewrite some of the text and delete the rest of the file This the code that I am trying to do

#include<iostream>
#include<fstream>

using namespace std;
int main(int argc, char **argv){
    fstream *binf;
    fstream someFile("t.txt", ios::binary|ios::out|ios::in);
    int i;
    for(i=0;i<3;i++){
        char c;
        someFile.seekg(i);
        someFile.get(c);
        cout<<"c:"<<c<<endl;
    }
    someFile.seekp(i++);
    someFile.put("Y");
    someFile.seekp(i++);
    someFile.put("Y");
    //Delete the rest of the file
    return 0;
}

Note the following flags for opening a file

ios::in Open for input operations.
ios::out    Open for output operations.
ios::binary Open in binary mode.
ios::ate    Set the initial position at the end of the file. If this flag is not set to any value, the initial position is the beginning of the file.
ios::app    All output operations are performed at the end of the file, appending the content to the current content of the file. This flag can only be used in streams open for output-only operations.
ios::trunc  If the file opened for output operations already existed before, its previous content is deleted and replaced by the new one.

I try many combinations of these but non of them help me to do what I want I want to read the file until I find text. If I find the text that I want, I over write it and delete the rest of the file. So, the file should be re-sized to smaller file.


回答1:


You can't do that with single stream object.

Possible solutions:

Either close your file and call truncate function, :

 #include <unistd.h>
 int ftruncate(int fildes, off_t length);
 int truncate(const char *path, off_t length); 

MS Windows version of truncate is _chsize - see http://msdn.microsoft.com/en-us//library/dk925tyb.aspx

int _chsize( 
   int fd,
   long size 
);

Or open your file for reading only, read/replace to some stringstream, then put everything to your file this time opened for overwriting:

fstream someFile("t.txt", ios::binary|ios::in);
stringstream ss;
// copy (with replacing) whatever needed from someFile to ss 
someFile.close();
someFile.open("t.txt", ios::binary|ios::out|ios::trunc);
someFile << ss.rdbuf();
someFile.close();


来源:https://stackoverflow.com/questions/13112026/overwriting-some-text-in-a-file-using-fstream-and-delete-the-rest-of-the-file

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!