代码之家  ›  专栏  ›  技术社区  ›  Arlington

C++删除或覆盖文件中的现有信息

  •  1
  • Arlington  · 技术社区  · 7 年前

    在C++中,有没有一种方法可以使用标准库覆盖一个大文件中的二进制数据,并在不首先加载整个文件的情况下保留文件中的其余现有数据?

    到目前为止我拥有的:

    #include <fstream>
    
    int main(int argc, char** argv)
    {
        std::fstream f;
        f.open("MyFile",std::ios::in);
        while (f.good())
        {
            char Current = f.get();
            if (Current == 'A')
                break;
        }
        int Location = f.gcount()-1;
        f.close();
    
        if (Location < 0)
        {
            printf("Nothing to do.\n");
            return EXIT_SUCCESS;
        }
        else
        {
            f.open("MyFile",std::ios::in | std::ios::out);
            f.seekp(Location);
            f.write("Q",1);
            //f.put('Q');
            //f << "Q";
            f.close();
            return EXIT_SUCCESS;
        }
    }
    

    这似乎现在起作用了——谢谢大家。

    1 回复  |  直到 7 年前
        1
  •  1
  •   nvoigt    7 年前

    std::ios::in | std::ios::out ,然后当您有了“A”的位置时,使用将“输入插入符号”移回该位置 f.seekg(Location); 并写入文件。

    请记住,您只能替换/覆盖。不能附加到文件的中间。

    这应该有效:

    #include <fstream>
    #include <iostream>
    
    int main()
    {
        std::fstream f("d:\\file.txt", std::ios::in | std::ios::out);
    
        char c;
    
        while (f >> c)
        {
            if (c == 'A')
            {
                f.seekp(-1, std::ios_base::cur);
                f.put('Q');
                return EXIT_SUCCESS;
            }
        }
    
        std::cout << "Nothing to do." << std::endl;
    
        return EXIT_SUCCESS;
    }