UNIX Socket FAQ

A forum for questions and answers about network programming on Linux and all other Unix-like systems

You are not logged in.

  • Index
  • » C++
  • » Need Inputs for reading file from specific offset

#1 2013-08-07 08:00 AM

santoshkumar
Member
Registered: 2007-08-21
Posts: 53

Need Inputs for reading file from specific offset

Can you correct me where i'm going wrong.

Requirement.

1. Need to open existing log file.

2. make note of current end of file(ref1).

3. call_processing_routine (this results in the log file writing ).

4. now read the log file begging at ref1(earlier eof) till the current eof.

Wrote this apparently this is not working.

using namespace std;
#include<iostream>


#include <fstream>

int main () {
string STRING;
fstream infile;
infile.open ("example.txt", ios::in);// | ios::nocreate);// | ios::ate );
if(!infile.is_open()) {
cout<<"error opening\n";
exit (1);
}
infile.seekp(0,ios::end);
getchar(); //During this will open the example.txt and add contents 
while(infile.good()) {
getline(infile,STRING);
cout<<STRING<<"\n";
}
infile.close();
}

Last edited by santoshkumar (2013-08-07 08:00 AM)

Offline

#2 2013-08-07 01:20 PM

RobSeace
Administrator
From: Boston, MA
Registered: 2002-06-12
Posts: 3,826
Website

Re: Need Inputs for reading file from specific offset

C++ isn't really my strong suit...  In straight C, I'd save the current EOF offset (obtained via ftell() or lseek()), then explicitly seek back to it again before resuming reading...  In fact, I'd close the file during the pause where I expected others to be writing to it, then reopen it after and seek to the previously saved offset...  That would cover you in case whatever writes to the file uses some kind of trickery like writing to a brand new file, then renaming atomically over the old one...  In that case, if you were to keep open the old file, you'd never see the new contents at all, since you'd have an open descriptor for a file that's now been removed from the filesystem...  I don't know if that's what's happening with your code or not, because you don't really specify how your code is "not working" exactly...

Offline

#3 2013-08-08 07:59 AM

santoshkumar
Member
Registered: 2007-08-21
Posts: 53

Re: Need Inputs for reading file from specific offset

This does the job.


using namespace std;
#include<iostream>
#include <fstream>

int main () {
         string STRING;
        ifstream infile;
        infile.open ("example.txt", ios::in | ios::ate );
        if(!infile.is_open()) {
           exit (1);
        }
  
        getchar();
        while(!infile.eof()) {
            getline(infile,STRING);
                 cout<<STRING<<"\n";
         }
        infile.close();
}

Thanks all for trying.

Offline

  • Index
  • » C++
  • » Need Inputs for reading file from specific offset

Board footer

Powered by FluxBB