简体   繁体   English

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

[英]C++ Seekp() in binary files is removing the data

I want to use seekp() function with binary files to modify the data of certain integer. I have made simple test program to test seekp funstion but it does not work rather it deletes the old content in file.我想使用带有二进制文件的 seekp() function 来修改某些 integer 的数据。我已经制作了简单的测试程序来测试 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;
}

#here are my steps i am doing to test it:# #这是我正在做的测试步骤:#
1)comment the outfile.seekp(4, std::ios::beg ); 1) 注释 outfile.seekp(4, std::ios::beg ); in code above then it will print the contents in file在上面的代码中,它将打印文件中的内容
2)now uncomment the seekp line and comment the two outfile.write() lines leaving one to test whetehr seekp is putting the pointer so i can write at exact loaction But when i do this the previous data lost 2)现在取消对 seekp 行的注释并注释两个 outfile.write() 行,留下一个来测试 whetehr seekp 是否放置了指针,这样我就可以在确切的位置写入但是当我这样做时,以前的数据丢失了
3)i then tried commenting all write lines leaving seekp lines uncommented and then i saw the whole file cintent is removed 3)然后我尝试评论所有写行,留下未注释的 seekp 行,然后我看到整个文件 cintent 被删除

WHat i am doing wrong i cant understand.我做错了什么我不明白。 I have tried seekp(sizeof(int), std::ios::beg) but it also doest not work.. Any help please我试过 seekp(sizeof(int), std::ios::beg) 但它也不起作用..请帮忙

You destroy content of file every time you open it, it has nothing to do with seekp .每次打开文件时都会破坏文件内容,这与seekp

std::ios::out means implicitly std::ios::trunc , unless there is std::ios::in or std::ios::app as well (yes, it's a mess). std::ios::out意味着隐式std::ios::trunc ,除非也有std::ios::instd::ios::app (是的,这是一团糟)。 See cppreference for detailed description of how flags work with each other.有关标志如何相互协作的详细描述,请参见cppreference

You need to open file in append mode and then seekp to position that interests you:您需要以 append 模式打开文件,然后seekp您感兴趣的 position:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM