【问题标题】:overwriting some text in a file using fstream and delete the rest of the file使用 fstream 覆盖文件中的某些文本并删除文件的其余部分
【发布时间】:2012-10-28 19:04:17
【问题描述】:

我正在尝试编写一个使用 fstream 读取文件的程序 然后,重写一些文本并删除文件的其余部分 这是我正在尝试做的代码

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

注意以下打开文件的标志

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.

我尝试了许多这些组合,但没有一个可以帮助我做我想做的事 我想阅读文件,直到找到文本。如果我找到我想要的文本,我会覆盖它并删除文件的其余部分。所以,文件应该被重新调整为更小的文件。

【问题讨论】:

    标签: c++ file fstream


    【解决方案1】:

    单流对象无法做到这一点。

    可能的解决方案:

    关闭您的文件并调用 truncate 函数:

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

    截断的 MS Windows 版本是 _chsize - 请参阅 http://msdn.microsoft.com/en-us//library/dk925tyb.aspx

    int _chsize( 
       int fd,
       long size 
    );
    

    或者以只读方式打开您的文件,读取/替换某些字符串流,然后将所有内容放入您的文件中,这次打开以进行覆盖:

    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();
    

    【讨论】:

    • unistd 是 c 标准库。有没有办法用 C++ 做到这一点。
    • 另一种方式需要一个缓冲区(非常大的缓冲区)。我正在用 MB 复制文件
    • @user1061392 如果您的目标系统支持此函数,您可以在 C++ 程序中调用 C 函数。
    • @user1061392 如果这是 MS Windows 然后试试这个:FILE* f = fopen(...); _chsize( fileno(f), newSize);
    • @user1061392 你被要求做的事情在标准 C++ 中是不可能的。我猜你误会了?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-11
    • 2016-06-19
    • 2018-03-19
    • 1970-01-01
    • 1970-01-01
    • 2011-11-27
    • 1970-01-01
    相关资源
    最近更新 更多