首页 > 解决方案 > 二进制文件中的 C++ Seekp() 正在删除数据

问题描述

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

// 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() 行,留下一个来测试 seekp 是否放置指针,以便我可以在确切位置写入但是当我这样做时以前的数据丢失了
3)然后我尝试注释所有写入行,使 seekp 行未注释,然后我看到整个文件 cintent 被删除

我做错了什么我无法理解。我试过 seekp(sizeof(int) , std::ios::beg) 但它也不起作用..请帮忙

标签: c++c++17

解决方案


每次打开文件时都会破坏文件的内容,它与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}; 

推荐阅读