473,657 Members | 2,504 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

File stream close followed by open leads to inconsistent behavior

I have been able to recreate a problem that I am having with the file
stream using the simple sample code given below.

I am trying to read the number of lines in a file, relying on the
getline method to read all the characters (including leading
whitespaces) until the new line character (the default line delimiter)
or end-of-file is reached. Then I close the stream, reopen it and
repeat the procedure. I get the correct answer only the first time.
The second time I get value of zero. This is with gcc version 3.3.1

Is this a compiler issue, or is this standard language feature?

Sample code follow

Thanks,
Song

///////////////////////////////////////////////////////////////////////
#include <iostream>
#include <fstream>
#include <stdlib.h>
#include <string>

using namespace std;

main(int argc, char* argv[])
{
if(argc < 2)
{
cerr << "usage: " << argv[0] << " <filename>" << endl;
exit(-1);
}

ifstream fileStrm(argv[1]);
if(!fileStrm)
{
cerr << "Cannot open file " << argv[1] << " ....aborting" << endl;
exit (-2);
}

// First pass
string token;
unsigned long nlCount = 0;
while(getline(f ileStrm, token))
nlCount++;
fileStrm.close( );
cout << nlCount << "\n";

// Second pass
fileStrm.open(a rgv[1]);
nlCount = 0;
while(getline(f ileStrm, token))
nlCount++;
fileStrm.close( );
cout << nlCount << "\n";

exit(0);
}

Aug 15 '06 #1
5 1989
Generic Usenet Account wrote:
I have been able to recreate a problem that I am having with the file
stream using the simple sample code given below.

I am trying to read the number of lines in a file, relying on the
getline method to read all the characters (including leading
whitespaces) until the new line character (the default line delimiter)
or end-of-file is reached. Then I close the stream, reopen it and
repeat the procedure. I get the correct answer only the first time.
The second time I get value of zero. This is with gcc version 3.3.1

Is this a compiler issue, or is this standard language feature?
I would call it a bug in your program...
>
Sample code follow

Thanks,
Song

///////////////////////////////////////////////////////////////////////
#include <iostream>
#include <fstream>
#include <stdlib.h>
#include <string>

using namespace std;

main(int argc, char* argv[])
int main(int argc, char* argv[])
{
if(argc < 2)
{
cerr << "usage: " << argv[0] << " <filename>" << endl;
exit(-1);
}

ifstream fileStrm(argv[1]);
if(!fileStrm)
{
cerr << "Cannot open file " << argv[1] << " ....aborting" << endl;
exit (-2);
}

// First pass
string token;
unsigned long nlCount = 0;
while(getline(f ileStrm, token))
nlCount++;

At this point 'fileStrm' is in bad state - end of file. Calling 'close'
does not change that.
fileStrm.close( );
cout << nlCount << "\n";

// Second pass
You might want to begin with

fileStrm.clear( );
fileStrm.open(a rgv[1]);
nlCount = 0;
while(getline(f ileStrm, token))
nlCount++;
fileStrm.close( );
cout << nlCount << "\n";

exit(0);
}

V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
Aug 15 '06 #2
Generic Usenet Account wrote:
Sample code follow

ifstream fileStrm(argv[1]);
if(!fileStrm)
{
cerr << "Cannot open file " << argv[1] << " ....aborting" << endl;
exit (-2);
}

Can someone please explain to me how instantiation of the input file
stream object can return a NULL? Sometime back I tried a similar
approach on a user-defined class. In the constructor I tried to set
the "this" pointer to NULL in case of an error. The intent was to
check for a NULL object at the point of invocation, in much the same
way as shown above. However, the compiler did not allow me to do that.
Furthermore, I was told by a C++ Guru that the way to handle errors in
object instantiation is to throw an exception.

How in the world do we then get away with returning a NULL object in
the case of an error in this case?

Thanks,
Masood

Aug 16 '06 #3
ma**********@ly cos.com wrote:
Generic Usenet Account wrote:
>Sample code follow

ifstream fileStrm(argv[1]);
if(!fileStrm)
{
cerr << "Cannot open file " << argv[1] << " ....aborting" <<
endl; exit (-2);
}


Can someone please explain to me how instantiation of the input file
stream object can return a NULL? Sometime back I tried a similar
approach on a user-defined class. In the constructor I tried to set
the "this" pointer to NULL in case of an error. The intent was to
check for a NULL object at the point of invocation, in much the same
way as shown above. However, the compiler did not allow me to do
that. Furthermore, I was told by a C++ Guru that the way to handle
errors in object instantiation is to throw an exception.

How in the world do we then get away with returning a NULL object in
the case of an error in this case?
'std::basic_ios ' (the base class for all streams) has an overloaded
operator void*, which returns a null pointer if 'fail()' returns true.

V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
Aug 16 '06 #4
In comp.lang.c++ ma**********@ly cos.com wrote:
Generic Usenet Account wrote:
>Sample code follow

ifstream fileStrm(argv[1]);
if(!fileStrm)
{
cerr << "Cannot open file " << argv[1] << " ....aborting" << endl;
exit (-2);
}

Can someone please explain to me how instantiation of the input file
stream object can return a NULL?
This answer in the FAQ is about the "while (std::cin >foo)" syntax,
but its explanation applies also to std::ifstream:

http://www.parashift.com/c++-faq-lit....html#faq-15.4

--
Marcus Kwok
Replace 'invalid' with 'net' to reply
Aug 16 '06 #5
On Tue, 15 Aug 2006 15:51:36 -0400 in comp.lang.c++, "Victor
Bazarov" <v.********@com Acast.netwrote,
> while(getline(f ileStrm, token))
nlCount++;


At this point 'fileStrm' is in bad state - end of file. Calling 'close'
does not change that.
Rather, a failed state. eofbit and failbit are set, not badbit.

Aug 16 '06 #6

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

Similar topics

8
9845
by: Brandon McCombs | last post by:
This may be the wrong group but I didn't see anything for VC++ so I'm trying here. I have a C++ book by Deitel and Deitel that says I can use fstream File("data.dat", ios::in | ios::out | ios::binary) to declare a file object with read/write modes turned on for working with binary data. I've tried this and my file is not created. The only time it is created is when I specify ifstream or ofstream but not fstream. I've tried removing the...
7
2249
by: Naren | last post by:
Hello All, Can any one help me in this file read problem. #include <stdio.h> int main() {
7
2570
by: PJ | last post by:
I have an open FileStream and I open a BinaryWriter on it. After writing to this file, I want to read it to another stream. FileStream fs = new FileStream(Path.GetTempFileName()); BinaryWriter bw = new BinaryWriterer(fs); // write data to a filestream bw.Close(); fs.Position = 0; // ** Exception, Object is disposed
12
5876
by: Adam J. Schaff | last post by:
I am writing a quick program to edit a binary file that contains file paths (amongst other things). If I look at the files in notepad, they look like: <gibberish>file//g:\pathtofile1<gibberish>file//g:\pathtofile2<gibberish> etc. I want to remove the "g:\" from the file paths. I wrote a console app that successfully reads the file and writes a duplicate of it, but fails for some reason to do the "replacing" of the "g:\". The code...
12
2965
by: Brian Henry | last post by:
first question... I have a flat file which unfortinuatly has columns seperated by nulls instead of spaces (a higher up company created it this way for us) is there anyway to do a readline with this and not have it affected by the null? because it is right now causes truncated data at wierd places... but as soon as i manually with a hex editor change char(00) to char(20) in the files it reads prerfectly... which leads me to my 2nd...
10
2373
by: Gunnar G | last post by:
I'm having problem reading from the beginning of a file. Here is the code (more or less) ifstream codefin; ofstream codefout; while (not_annoyed)
1
19919
by: ABCL | last post by:
Hi All, I am working on the situation where 2 different Process/Application(.net) tries to open file at the same time....Or one process is updating the file and another process tries to access it, it throws an exception. How to solave this problem? So second process can wait until first process completes its processing on the file. Thanks in advance
17
8018
by: Peter Duniho | last post by:
I searched using Google, on the web and in the newsgroups, and found nothing on this topic. Hopefully that means I just don't understand what I'm supposed to be doing here. :) The problem: I am trying to use the SaveFileDialog class to get a filename, which is subsequently opened for writing (write access, read sharing, but using read/write sharing doesn't make the problem go away anyway). Sometimes, on the statement where I...
14
2799
by: prasadjoshi124 | last post by:
Hi All, I am writing a small tool which is supposed to fill the filesystem to a specified percent. For, that I need to read how much the file system is full in percent, like the output given by df -k lopgod10:~/mycrfile # df -k /mnt/mvdg1/vset Filesystem 1K-blocks Used Available Use% Mounted on
0
8421
marktang
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 usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8325
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 synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8844
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
8518
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 most users, this new feature is actually very convenient. If you want to control the update process,...
0
8621
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 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 choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
6177
isladogs
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 instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
4330
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2743
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
2
1971
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.