Muhammad Jamshaid
Muhammad Jamshaid

Reputation: 5

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.

// 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 ); 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
3)i then tried commenting all write lines leaving seekp lines uncommented and then i saw the whole file cintent is removed

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

Upvotes: 0

Views: 461

Answers (1)

Yksisarvinen
Yksisarvinen

Reputation: 22364

You destroy content of file every time you open it, it has nothing to do with 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). See cppreference for detailed description of how flags work with each other.

You need to open file in append mode and then seekp to position that interests you:

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

Upvotes: 1

Related Questions