Solved

Read/Write on a File

Posted on 2000-02-23
13
181 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 

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

Enroll in June's Course of the Month

June’s Course of the Month is now available! Experts Exchange’s Premium Members, Team Accounts, and Qualified Experts have access to a complimentary course each month as part of their membership—an extra way to sharpen your skills and increase training.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Errors will happen. It is a fact of life for the programmer. How and when errors are detected have a great impact on quality and cost of a product. It is better to detect errors at compile time, when possible and practical. Errors that make their wa…
This article will show you some of the more useful Standard Template Library (STL) algorithms through the use of working examples.  You will learn about how these algorithms fit into the STL architecture, how they work with STL containers, and why t…
The viewer will learn how to clear a vector as well as how to detect empty vectors in C++.
The viewer will be introduced to the member functions push_back and pop_back of the vector class. The video will teach the difference between the two as well as how to use each one along with its functionality.

729 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