472,811 Members | 1,115 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 472,811 software developers and data experts.

File Reading Question

First: sorry as a relative newbie for previously not including code.
My question:
Reading C++ books I almost always find programs such as the one below
give the following type of code for reading a file :

//********* BUM CODE *************************************
infile.open ("test.dat" , ios::in);

while (!infile.eof())
{
infile.read ((char *)&dog, sizeof (dog)); // read from file
cout << "Dog Name = " << dog.name << endl;
cout << "Dog age = " << dog.age << endl;
cout << "Dog weight = " << dog.weight << endl;
}
infile.close();
//************************************************** ****************
If you use this you find that the last record to be read is always
displayed twice!
Nowhere in the books can I find a mention, nor a solution to this.
My solution .. and I am always looking for the simplest to understand ..
is to use the 'read-ahead' technique to read the file

//***** READ AHEAD METHOD ****************************
infile.open ("test.txt" , ios::in);

infile.read ((char *)&dog, sizeof (dog)); // read ahead first record

while (!infile.eof())
{
cout << "Dog Name = " << dog.name << endl;
cout << "Dog age = " << dog.age << endl;
cout << "Dog weight = " << dog.weight << endl;
infile.read ((char *) &dog, sizeof (dog)); // read next record
}
infile.close();
//***********************************
This appears to work .. but as I have not seen this used anywhere I
wondered if there is anything wrong with it as a method?
Is there a better way?

//****** FULL BUM PROGRAM ****************************
#include <fstream>
#include <cstdlib>
#include <ctype.h> // needed for toupper()
#include <string>

using namespace std;

void StoreFileData(fstream& outfile);
void RetrieveFileData(fstream& infile);

class doggie // used basically as a structure
{
public:
char name[20] ;
int age;
float weight ;
};
//***********************************
int main()
{
fstream f;

StoreFileData(f);
RetrieveFileData(f);

system("PAUSE");
return 0;
}
//************************************
void StoreFileData(fstream& outfile)
{
doggie dog ;
char answer = 'Y';

outfile.open ("test.txt" , ios::out);

do
{
cout << "Enter dog name :";
cin >> dog.name;

cout << "What is " << dog.name << "\'s age : " ;
cin >> dog.age;
cout << "What is " << dog.name << "\'s weight : " ;
cin >> dog.weight;
outfile.write ((char *)&dog, sizeof (dog));
cout << "\nAny more dogs (y/n)?: ";
cin >> answer ;
answer = toupper (answer);
}
while (answer != 'N');
outfile.close();
}
//***********************************************
void RetrieveFileData(fstream& infile)
{
doggie dog ;

cout << "\nReading the file back now " << endl;

infile.open ("test.txt" , ios::in);

while (!infile.eof())
{
infile.read ((char *)&dog, sizeof (dog)); // read record

cout << "Dog Name = " << dog.name << endl;
cout << "Dog age = " << dog.age << endl;
cout << "Dog weight = " << dog.weight << endl;
}
infile.close();
}
//***********************************

Jul 22 '05 #1
2 2494
Brian Ward wrote:
First: sorry as a relative newbie for previously not including code.
My question:
Reading C++ books I almost always find programs such as the one below
give the following type of code for reading a file :

//********* BUM CODE *************************************
infile.open ("test.dat" , ios::in);

while (!infile.eof())
{
infile.read ((char *)&dog, sizeof (dog)); // read from
file cout << "Dog Name = " << dog.name << endl;
cout << "Dog age = " << dog.age << endl;
cout << "Dog weight = " << dog.weight << endl;
}
infile.close();
//************************************************** ****************
If you use this you find that the last record to be read is always
displayed twice!
That's because that usage is wrong! eof() doesn't return true until
_after_ you tried to read past the end of the file. So when your last
read operation reached the end, eof() will still be false, and the loop
is executed once more, but there is no data left. The next read
operation fails, your stream goes into eof() state, but the additional
loop iteration has already been done before the loop ends.
Nowhere in the books can I find a mention, nor a solution to this.
My solution .. and I am always looking for the simplest to understand
.. is to use the 'read-ahead' technique to read the file

//***** READ AHEAD METHOD ****************************
infile.open ("test.txt" , ios::in);

infile.read ((char *)&dog, sizeof (dog)); // read ahead first
record

while (!infile.eof())
{
cout << "Dog Name = " << dog.name << endl;
cout << "Dog age = " << dog.age << endl;
cout << "Dog weight = " << dog.weight << endl;
infile.read ((char *) &dog, sizeof (dog)); // read next
record
}
infile.close();
//***********************************
This appears to work .. but as I have not seen this used anywhere I
wondered if there is anything wrong with it as a method?
Is there a better way?


Try:

infile.open ("test.dat" , ios::in);

while (infile.read ((char *)&dog, sizeof (dog)))
{
cout << "Dog Name = " << dog.name << endl;
cout << "Dog age = " << dog.age << endl;
cout << "Dog weight = " << dog.weight << endl;
}
infile.close();

if (infile.eof())
; // ok, end of file reached
else
std::cout << "error\n"; // some read error happened
That's the typical outline of reading a file in C++.

Jul 22 '05 #2
On Tue, 20 Jan 2004 22:33:59 GMT in comp.lang.c++, Brian Ward
<br********@zetnet.co.uk> was alleged to have written:
Reading C++ books I almost always find programs such as the one below
give the following type of code for reading a file : while (!infile.eof())


Please post the author, title, and page# of the offending book(s)!

This issue is covered in Marshall Cline's C++ FAQ. See topic "[15.4]
Why does my input seem to process past the end of file?" It is always
good to check the FAQ before posting. You can get the FAQ at:
http://www.parashift.com/c++-faq-lite/
Jul 22 '05 #3

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
by: Xah Lee | last post by:
# -*- coding: utf-8 -*- # Python # to open a file and write to file # do f=open('xfile.txt','w') # this creates a file "object" and name it f. # the second argument of open can be
1
by: Marc Cromme | last post by:
I would like to ask a question about (good ?) style and possibilities in mixing C FILE* and C++ file streams. The background is that I want to use the C libpng library from within C++, but I...
0
by: Lokkju | last post by:
I am pretty much lost here - I am trying to create a managed c++ wrapper for this dll, so that I can use it from c#/vb.net, however, it does not conform to any standard style of coding I have seen....
7
by: John Dann | last post by:
I'm trying to read some binary data from a file created by another program. I know the binary file format but can't change or control the format. The binary data is organised such that it should...
2
by: archana | last post by:
Hi all, I am new to asp.net (learning phase). I have to develop application in asp.net to read file from client pc and display statistics of that file to client. So my question is that to...
6
by: electrixnow | last post by:
in VC++ Express Edi Is their a way to replace one line of TEXT in an existing text file. I now open it then read in the data, once I have found somthing that needs updating, I need to overwrite...
9
by: FFMG | last post by:
In my site I have a config table, (MySQL), with about 30 entries; the data is loaded on every single page load. This is not the only call to the db, (we do a total of about 8 calls to the db). As...
1
AdrianH
by: AdrianH | last post by:
Assumptions I am assuming that you know or are capable of looking up the functions I am to describe here and have some remedial understanding of C programming. FYI Although I have called this...
31
by: broli | last post by:
I need to parse a file which has about 2000 lines and I'm getting told that reading the file in ascii would be a slower way to do it and so i need to resort to binary by reading it in large...
0
by: erikbower65 | last post by:
Using CodiumAI's pr-agent is simple and powerful. Follow these steps: 1. Install CodiumAI CLI: Ensure Node.js is installed, then run 'npm install -g codiumai' in the terminal. 2. Connect to...
0
linyimin
by: linyimin | last post by:
Spring Startup Analyzer generates an interactive Spring application startup report that lets you understand what contributes to the application startup time and helps to optimize it. Support for...
0
by: erikbower65 | last post by:
Here's a concise step-by-step guide for manually installing IntelliJ IDEA: 1. Download: Visit the official JetBrains website and download the IntelliJ IDEA Community or Ultimate edition based on...
2
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Sept 2023 starting at 18:00 UK time (6PM UTC+1) and finishing at about 19:15 (7.15PM) The start time is equivalent to 19:00 (7PM) in Central...
0
by: Taofi | last post by:
I try to insert a new record but the error message says the number of query names and destination fields are not the same This are my field names ID, Budgeted, Actual, Status and Differences ...
0
by: Rina0 | last post by:
I am looking for a Python code to find the longest common subsequence of two strings. I found this blog post that describes the length of longest common subsequence problem and provides a solution in...
5
by: DJRhino | last post by:
Private Sub CboDrawingID_BeforeUpdate(Cancel As Integer) If = 310029923 Or 310030138 Or 310030152 Or 310030346 Or 310030348 Or _ 310030356 Or 310030359 Or 310030362 Or...
0
by: lllomh | last post by:
Define the method first this.state = { buttonBackgroundColor: 'green', isBlinking: false, // A new status is added to identify whether the button is blinking or not } autoStart=()=>{
0
by: Mushico | last post by:
How to calculate date of retirement from date of birth

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.