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(f stream& outfile);
void RetrieveFileDat a(fstream& infile);
class doggie // used basically as a structure
{
public:
char name[20] ;
int age;
float weight ;
};
//*************** *************** *****
int main()
{
fstream f;
StoreFileData(f );
RetrieveFileDat a(f);
system("PAUSE") ;
return 0;
}
//*************** *************** ******
void StoreFileData(f stream& 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 RetrieveFileDat a(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();
}
//*************** *************** ***** 2 2535
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++.
On Tue, 20 Jan 2004 22:33:59 GMT in comp.lang.c++, Brian Ward
<br********@zet net.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/ This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
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
|
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 would like to open C++ file streams due to easier exception
handeling and safe closure of file ressources.
Question 1:
I open a standard file...
|
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. It is
almost like it is trying to implement it's own COM interfaces...
below is the header, and a link to the dll+code:
Zip file with header,...
|
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 populate a
series of structures of specified variable composition.
I have the structures created OK, but actually reading the files is
giving me an...
|
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 read file from client pc do i need to upload
that file on server and then start reading that file.
Or is there any other alternative for this.
| |
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
that one line only and continue reading the rest of the file to check
for other line that
may need updates.
|
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 with many configurations settings, once the options are set the
values will not change much.
So I thought it would be a good idea to move the data...
|
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 article “How to Parse a File in C++”, we are actually mostly lexing a file which is the breaking down of a stream in to its component parts,...
|
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 chunks. Can any
one please explain what is all
this about ?
|
by: marktang |
last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main...
|
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it.
First, let's disable language...
| |
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 Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
|
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 protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
|
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, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
|
by: isladogs |
last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM).
In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules.
He will explain when you may want to use classes...
|
by: TSSRALBI |
last post by:
Hello
I'm a network technician in training and I need your help.
I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs.
The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols.
I succeeded, with both firewalls in...
|
by: 6302768590 |
last post by:
Hai team
i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
| |
by: muto222 |
last post by:
How can i add a mobile payment intergratation into php mysql website.
| |