Solved

Read/Write on a File

Posted on 2000-02-23
13
177 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
Netscaler Common Configuration How To guides

If you use NetScaler you will want to see these guides. The NetScaler How To Guides show administrators how to get NetScaler up and configured by providing instructions for common scenarios and some not so common ones.

 

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

NAS Cloud Backup Strategies

This article explains backup scenarios when using network storage. We review the so-called “3-2-1 strategy” and summarize the methods you can use to send NAS data to the cloud

Question has a verified solution.

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

What is C++ STL?: STL stands for Standard Template Library and is a part of standard C++ libraries. It contains many useful data structures (containers) and algorithms, which can spare you a lot of the time. Today we will look at the STL Vector. …
Many modern programming languages support the concept of a property -- a class member that combines characteristics of both a data member and a method.  These are sometimes called "smart fields" because you can add logic that is applied automaticall…
The goal of the tutorial is to teach the user how to use functions in C++. The video will cover how to define functions, how to call functions and how to create functions prototypes. Microsoft Visual C++ 2010 Express will be used as a text editor an…
The viewer will be introduced to the technique of using vectors in C++. The video will cover how to define a vector, store values in the vector and retrieve data from the values stored in the vector.

777 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