提问者:小点点

二进制文件中的C++Seekp()正在删除数据


我想在二进制文件中使用seekp()函数来修改某个整数的数据。 我做了一个简单的测试程序来测试seekp功能,但它不工作,而是删除文件中的旧内容。

// position in output stream
#include <fstream>      // std::ofstream
#include <iostream>

int main() {

    std::ofstream outfile{"test.dat" ,std::ios::binary| std::ios::out};
    struct t {
        int x;
        
    };
    t t1{ 36};
    t t2{ 2 };
    t t3{ 3 };
    
    outfile.seekp(4 , std::ios::beg );
    outfile.write((char*)&t1 , sizeof(t1));
    outfile.write((char*)&t2, sizeof(t2));
    outfile.write((char*)&t3, sizeof(t3));
    

    outfile.close();

    std::ifstream iutfile{ "test.dat" ,std::ios::binary  };
    t read;
    while (iutfile.read((char*)&read, sizeof(read)))
    {
        std::cout << "\n\n\t" << read.x;
    }
    iutfile.close();
    return 0;
}

#下面是我测试它的步骤:#
1)注释Outfile.seekp(4,std::ios::beg);然后在上面的代码中,它将打印文件中的内容
2)现在取消注释seekp行,并注释两个Outfile.write()行,留下一个来测试hr seekp是否正在放置指针,以便我能够以精确的操作写入,但是当我这样做时,以前的数据丢失
3)我然后尝试注释所有写入行,使seekp行未注释,然后我看到整个文件centent被删除

我不明白我做错了什么。 我试过seekp(sizeof(int),std::iOS::beg),但它也不起作用。 有什么需要帮助的吗


共1个答案

匿名用户

每次打开文件时都会销毁文件内容,这与seekp无关。

std::iOS::out隐式地表示std::iOS::trunc,除非也有std::iOS::instd::iOS::app(是的,很乱)。 有关标志如何相互工作的详细说明,请参阅cppreference。

您需要在追加模式下打开文件,然后seekp定位您感兴趣的位置:

std::ofstream outfile{"test.dat" ,std::ios::binary | std::ios::app}; //out is optional 
std::ofstream outfile{"test.dat" ,std::ios::binary | std::ios::app | std::ios::out}; 

相关问题


MySQL Query : SELECT * FROM v9_ask_question WHERE 1=1 AND question regexp '(二进制|文件|中|c++seekp|删除|数据)' ORDER BY qid DESC LIMIT 20
MySQL Error : Got error 'repetition-operator operand invalid' from regexp
MySQL Errno : 1139
Message : Got error 'repetition-operator operand invalid' from regexp
Need Help?