fstream File i/o

M

Mike Copeland

I am trying to convert some applications to be "more C++" and use
safer I/o. The code below works, but it poses an annoyance: the last
record "read" from the input file has no content. Therefore, I must
include the "if(line.length())" code before writing any data to the
output file, because failing to do that adds a zero-length record to the
end of the output file.
What am I missing in this logic that would avoid adding the code?
TIA

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

int main ()
{
string line;
fstream f1, f2;
f1.open("pat12.n00", fstream::in);
if(f1.is_open())
{
f2.open("test.txt", fstream::eek:ut);
do
{
getline(f1, line);
if(line.length()) f2 << line << endl;
} while(!f1.eof());
f1.close();
f2.close();
}
else cout << "Unable to open file";

return 0;
}
 
J

Joshua Maurice

   I am trying to convert some applications to be "more C++" and use
safer I/o.  The code below works, but it poses an annoyance: the last
record "read" from the input file has no content.  Therefore, I must
include the "if(line.length())" code before writing any data to the
output file, because failing to do that adds a zero-length record to the
end of the output file.
   What am I missing in this logic that would avoid adding the code?
TIA

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

int main ()
{
  string   line;
  fstream  f1, f2;
  f1.open("pat12.n00", fstream::in);
  if(f1.is_open())
  {
    f2.open("test.txt", fstream::eek:ut);
    do
    {
      getline(f1, line);
      if(line.length()) f2 << line << endl;
    } while(!f1.eof());
    f1.close();
    f2.close();
  }
  else cout << "Unable to open file";

  return 0;
}

You must check whether the read succeeded before using the results of
the read. The idiomatic way is:
string line;
while (getline(f1, line))
{
//use line
}

".eof()" returns when eof has been reached. A getline can successfully
read characters into "line" and set "eof".

Short version: You should check the "fail" flag, which is set when no
further characters can be read, such as when eof is reached and no
characters were read in this operation before eof was reached. The
(effective) implicit conversion to bool in "while (getline(f1, line))"
does a check of the "fail" flag after doing the read operation.

Check your favorite C++ reference for the full semantics.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,754
Messages
2,569,529
Members
45,001
Latest member
Kendra00E1

Latest Threads

Top