Aravind .KEN Aravind .KEN - 2 months ago 6
C++ Question

How to read beginning of a file after reaching its end?

let my file contain: (file name:PROFILE.txt)

1 2 3 4 5`


I use the below code to read and get the data

#include <iostream>
#include <fstream>
using namespace std;
fstream profile;
int n;
int main()
{
profile.open("PROFILE.txt",ios::app|ios::in|ios::out); // file name is PROFILE.txt
long start = profile.tellg(); //marks the point of beginning of the file
a:
profile>>n;
long p = profile.tellg(); //marks the current point of the file cursor
cout<<n<<" "<<p<<endl;
if(n==5)profile.seekg(start); // or if(p==-1)profile.seekg(start);
goto a;
return 0;
}


Output was:

1 1
2 3
3 5
4 7
5 -1
5 -1
5 -1
5 -1
..
...
.... //so on


But, EXPECTED OUTPUT (or the output that I want):

1 1
2 3
3 5
4 7
5 9
1 1
2 3
3 5
4 7
5 9
1 1
2 3
3 5
4 7
5 9
.
..
... //so on


PROBLEM:
The problem is after it reaches the end of the file! it fails to go to the beginning of the file! and fails to obey seekg();! But suppose if the it didn't reach its end it works fine has it should!

What is my mistake and how to fix it! and what should be the code?

Please Note: I am c++ beginner! so please try to answer me by simple C++ program code and please try to answer me by step by step!

I hope you understand my program and my question!

PICTURE of my CODE,OUTPUT,FILE

After Serge Ballesta code fix

PLEASE NOTE that the following codes and outputs are from CODE:BLOCKS (latest version) running in Windows 10 (64 bit) PC (others info: i7 Processor, RAM: 16GB,GPU: 4GB)

TO SEE MY OTHER Questions

Answer

FIXED CODE:

    #include <iostream>
    #include <fstream>
    using namespace std;
    fstream profile;
    int n;
int long count_numbers ( int long num) //to count no of digits stored or entered in an int
 {
   int count =0;
   while (num !=0)
    {
      count++;
      num/=10;
    }
   return count;
 }

int main()
        {
            profile.open("PROFILE.txt",ios::app|ios::in|ios::out);
            a:
            long past= profile.tellg(); 
            profile>>n;
            long p= profile.tellg();
           if (p == -1) //thanks to Serge Ballesta
            {
                        profile.clear();
                        profile.seekg(0);
                   p=past+count_numbers(n)+1; // +1 to add space
            }
                cout<<n<<" "<<p<<endl;
            goto a;
            return 0;
        }

PROGRAM OUTPUT

Special thanks to Serge Ballesta (for his help and for his segment of his code)

IF THERE IS BETTER AND SMALLER AND SIMPLER WAY THAN THIS! PLEASE LET ME KNOW!

If you cant understand my code! pls feel to comment!or feel free to edit my answer in the better way! thank you!

                ***Special thanks to Stack Overflow community*** 

found really useful

Comments