Solved

Read/Write on a File

Posted on 2000-02-23
13
175 Views
Last Modified: 2010-04-02
Hey Folks, I have a problem in reading from a file that is constantly changing. If its ufolk123 I haven't implmented your func, but I have come up with my solution which works though with some errors. Can anyone tell me where is the bug, as I am unable to trace it.
I appreicate that.
Heres the code
=============================
int main()
{
 FILE *fFile;
 string str;
 char szPath[24]="C:\\file.dat";      
 if((fFile  = fopen(szPath,"r" ))== NULL )
   printf( "The file 'data' was not opened\n" );
      int ch;  
      int offset=0;
      int result,idx=0;
      do
      {
          ch =getc(fFile);
       if(ch==EOF)
       {
        _sleep(2000);
         result=
            fseek(fFile,offset+1,0);
        if(result)
         {
           printf("Fseek failed\n");
            break;
         }
      }
      if(ch=='\n')
      {
        printf("%s\n",str.c_str());
        str.erase();
      }
      else
      {
        str+=ch;
        offset++;
      }

    }while(1);
      
  return 0;

}

================================
0
Comment
Question by:vesel
  • 7
  • 6
13 Comments
 
LVL 22

Expert Comment

by:nietod
ID: 2552848
You should not be using the old C file streams for new programming (unless you need to maintain C compatibility.)  You woudl be wise to switch to C++ files stream (fstream) objects.

what is it that you are tryign to do?

IIt looks like you might be using

  fseek(fFile,offset+1,0);

after the end of the file was reached.  How do you know the file has gotten longer before you do this.  If it hasn't be appended to by another source, then the file length will be the same and this positions the file pointer past the end of the file.  This is legal, but not useful--for your case.
0
 

Author Comment

by:vesel
ID: 2552859
I will try going thru ifstream class. The problem is I started this approach earlier but it got messed up, so I am trying using the old low level stuff.
The basic logic is to read the file thats constantly changing from the point where you left last.I know I can get the last position of the file using tellg() and then use seekg to goto that point and read again using getline,but for some god damn reason its not working. If you can write a little working snippet I would be really thxful and also transfer the 125 points in your account.

TIA
0
 
LVL 22

Accepted Solution

by:
nietod earned 25 total points
ID: 2552888
>> trying using the old low level stuff.
There really isn't any advantage.

What was the mess up?

try

fstream Fil("filename.txt",ios_base::in);
int LasEOF = 0;

while (true)
{
    int CurEOf = Fil.seekg(0,ios_base::end);

    if (CurEOF != LasEOF) // If file is now longer.
    {
        Fil.seekg(o,ios_base::cur);
        // read the data here.
        LasEOF = CurEOF; // Save new length.
    }
    sleep(1000);
}
0
 

Author Comment

by:vesel
ID: 2555583
Thx neitod I will test your code and let you know.
heres what I have done that has gone a mess
=====================================
int main()
{

      ifstream fin("C:\\file.dat");
      if(!fin)
      {
            printf("Error Opening the File\n");
            return 0;
      }
      char buf[128];
      long cnt;      
      streampos nPos;
label:
      while(1)
      {
            fin.getline(buf,sizeof(buf));
            //send to the Queue
            printf("%s\n",buf);
            nPos=fin.tellg();
            if(nPos>0)
                  cnt=nPos;
            else
                  break;

      }

      if(!fin.good())
      {
            _sleep(200);
            // Resume back
            cnt      +=1;
            fin.seekg(cnt,ios::beg);
            fin.setstate((bool)ios::good);
            goto label;
      }

      printf("Hello World!\n");
      return 0;
}
=================================
0
 
LVL 22

Expert Comment

by:nietod
ID: 2555716
First of all, I strongly strongly suggest you get rid of the goto.  Just add an additional loop there.

Also used of 1 and 0 for booleans is strongly discouraged (assuming you have a compiler that supports bool.  you should use "true" and "false" instead.  it is clearer and does not require conversions.

What are you trying to do here

nPos=fin.tellg();
if(nPos>0)
0
 

Author Comment

by:vesel
ID: 2555828
OK I will do that thx for the suggestion. What happens if the getline func fails as there are no more lines in the file nPos returns the value -1. So I wanna store the last value of the nPos thru cnt which is the end of the file in one session. Then I forcefully change the bit to good so that it can goto the while loop for reading the file from the position where it left as the new lines are appended at the end of the file.
By the way the code which you had sent me earlier didn't worked so I am on ground 0.
0
Maximize Your Threat Intelligence Reporting

Reporting is one of the most important and least talked about aspects of a world-class threat intelligence program. Here’s how to do it right.

 
LVL 22

Expert Comment

by:nietod
ID: 2555861
I don't see how the code even begins to do what you suggest.

what does

nPos=fin.tellg();
 if(nPos>0)

do?

Why go back to the start in

fin.seekg(cnt,ios::beg);


The code I suggested should be very close to what you need.  What was wrong with it?
0
 

Author Comment

by:vesel
ID: 2558910
Neitod please give me your email I will send you the code that I have done. I have 2 program one that write to the file sleeps and then resumes. And the other one reads from the fil.

Thx
0
 
LVL 22

Expert Comment

by:nietod
ID: 2559112
its nietod@journey.com, but is there any reason you can't post the code here?
0
 

Author Comment

by:vesel
ID: 2560064
Ok I will post it here! thx by the way.
=======================================
int main(int argc, char* argv[])
{
      char szPath[32]="C:\\file.dat";
      FILE *fFile;
      ofstream fout("C:\\testresult.dat");
      char buf[128];int offset=0,result;
      fFile=fopen(szPath,"r");
      do
      {
            
            fgets(buf,sizeof(buf),fFile);
            offset++;
            if(feof(fFile))
            {
             _sleep(200);
              result=fseek(fFile,offset+1,0);
            if(result)
                  printf("Fseek failed\n");
            
            }
            
            cout<<buf;
            fout<<buf;


      }while(1);


      return 0;
}

=====================================
Please send me you expert comments
=================================
Heres the program that populates the file. You can start and exit this program to test whehter the other one picks the place where it left last(thats the whole objective of the Program)
int main(int argc, char* argv[])
{
      ofstream fout("C:\\file.dat");
      int idx=0;
      do
      {
            cout<<"Message written ["<<idx<<"]"<<endl;
            fout<<"Message written ["<<idx<<"]"<<endl;
            idx++;
            _sleep(100);
      }while(1);

      fout.close();
      
      return 0;
}

0
 
LVL 22

Expert Comment

by:nietod
ID: 2560917
By posting here it keeps the code in the EE database for everyone else to see.

But

fgets(buf,sizeof(buf),fFile);  

reads up to 128 byts and then you do

                offset++;

    result=fseek(fFile,offset+1,0);

why?  That doesn't take you to where you were last reading?

Now the code I posted before has a design that should work.  It constantly checks to see if the file has gotten longer than the spot where it last read.  if so, it reads again.  There may be an error or two in the code, but the basic design is sound, you code doesn't seem to have a sound foundation.
0
 

Author Comment

by:vesel
ID: 2562641
Thx for the comment
fgets(buf,sizeof(buf),fFile);  

                   reads up to 128 byts and then you do

                                   offset++;

                       result=fseek(fFile,offset+1,0);
The whole objective of this is to make sure to set the pointer to 1 position more than the last one. Incase when the ntwk is down and you wanna read the file again. the fseek will take you to the the next line from where you last left.
Did you ran the program ?? if so can U do if you have time.  Please comment on the prgam thereafter.

TIA
0
 
LVL 22

Expert Comment

by:nietod
ID: 2562661
>> the fseek will take you to the the
>> next line from where you last left.
But it won't.  It isn't based on lines.  it is based on bytes (characters).

Say the file starts at 128 bytes long.
You read the first 128 bytes and then reach the end of the file.
You increment offset by one to get one.  
Then you seek to offset plus one which is two.
Then you read again at offset two.  You already read that data at the start.

I don't have to run the program to know it makes no sense.  
0

Featured Post

IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

Unlike C#, C++ doesn't have native support for sealing classes (so they cannot be sub-classed). At the cost of a virtual base class pointer it is possible to implement a pseudo sealing mechanism The trick is to virtually inherit from a base class…
This article shows you how to optimize memory allocations in C++ using placement new. Applicable especially to usecases dealing with creation of large number of objects. A brief on problem: Lets take example problem for simplicity: - I have a G…
The viewer will learn how to use the return statement in functions in C++. The video will also teach the user how to pass data to a function and have the function return data back for further processing.
The viewer will learn how to user default arguments when defining functions. This method of defining functions will be contrasted with the non-default-argument of defining functions.

760 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

26 Experts available now in Live!

Get 1:1 Help Now