How to move file pointer to the beginning of the file in C++

1 Answer

0 votes
#include <iostream>
#include <fstream>

struct Example {
    float x, y;
};

int main(void)
{
    Example ex = { 0, 0 };

    std::ifstream ifs;
    ifs.open("data.txt");
    if ( !ifs ) {
        std::cout << "error opening file";
        exit(1);
    }
        
    ifs >> ex.x >> ex.y;
    std::cout << ex.x << ", " << ex.y << "\n";

    ex.x = 0;
    ex.y = 0;

    ifs.seekg(0, std::ios::beg); // move to beginning of the file 

    ifs >> ex.x >> ex.y;
    std::cout << ex.x << ", " << ex.y << "\n";

    ifs.close();

    
}


// data.txt
// --------
// 3.14 17.25


/*
run:

3.14, 17.25
3.14, 17.25

*/



 



answered Jan 29, 2023 by avibootz
...