473,396 Members | 1,827 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,396 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 2524
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: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...

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.