473,715 Members | 6,082 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Cannot reread file

I am having some trouble rereading a file for input. Here's the
problem: I have a text file with some data (football scores) in its
lines. First I read them line-by line to figure out how many lines it
has. Afterwards I want to read them again, and this time do some
processing. However I cannot make my program do this. I tried the
following:

############### #############

#include <iostream>
#include <fstream>
#include <string>

using namespace std;

int main()
{
ifstream inGameFile;

inGameFile.open ( "scores.txt ", ios::in );
if ( !inGameFile)
{
cerr << "Failed to open(1).\n";
exit(1);
}

const int LINE = 100;
char stLine[LINE+1];

// count the number of games
int nGames = 0;
while ( inGameFile.getl ine(stLine, LINE) )
{
nGames++;
}
cout << "A total of " << nGames << " games played.\n";
// Everything works fine this far

if ( !inGameFile)
{
cerr << "No longer open(2).\n"; // inGameFile no longer defined!
//exit(1);
}

cout << inGameFile.tell g() << endl; // result is -1
inGameFile.seek g( 0, ios::beg );
cout << inGameFile.tell g() << endl; // result is -1 again!

// Does not work this way; try to close and reopen:
inGameFile.clos e();
if ( !inGameFile)
{
cerr << "Failed to close(3).\n";
//exit(1);
}

inGameFile.open ( "scores.txt ", ios::in );
if ( !inGameFile)
{
cerr << "Failed to open(4).\n";
//exit(1);
} inGameFile.open ( "scores.txt ", ios::in );

}

############### #############

The output is:

A total of 1363 games played.
No longer open(2).
-1
-1
Failed to close(3).
Failed to open(4).

############### #############

Compiler is c++ (GCC) 3.2.2 20030222 (Red Hat Linux 3.2.2-5)

I did something similar on gnu c++ 2.95 under windows, where I could
resolve it by closing and reopening the file. This time it does not
work.

It seems that my inGameFile is automatically closed when I read the
last line, and I can neither move the get pointer nor re-open the
file.

Can someone explain me how can I overcome this?

Thanks,
Sanyi
Jul 19 '05 #1
5 4902

"Sanyi" <be******@hotma il.com> wrote in message
news:e3******** *************** ***@posting.goo gle.com...
I am having some trouble rereading a file for input. Here's the
problem: I have a text file with some data (football scores) in its
lines. First I read them line-by line to figure out how many lines it
has. Afterwards I want to read them again, and this time do some
processing. However I cannot make my program do this. I tried the
following:

############### #############

#include <iostream>
#include <fstream>
#include <string>

using namespace std;

int main()
{
ifstream inGameFile;

inGameFile.open ( "scores.txt ", ios::in );
Note: 'ifstream' has a 'mode' of ios::in by default.
What you wrote will work, but it's redundant.
if ( !inGameFile)
{
cerr << "Failed to open(1).\n";
exit(1);
}

const int LINE = 100;
char stLine[LINE+1];
Why not a std::string instead of an array?
Then you won't be limited to a size of 'LINE'.

// count the number of games
int nGames = 0;
while ( inGameFile.getl ine(stLine, LINE) )
{
nGames++;
}
cout << "A total of " << nGames << " games played.\n";
// Everything works fine this far

At this the stream 'inGameFile' is in a 'fail'
state (either because there was an error inside
the 'while' loop above, or it has reached end of
file). This state remains until explicitly reset.
if ( !inGameFile)
So this will always be true.
{
cerr << "No longer open(2).\n"; // inGameFile no longer defined!
No. The stream is still open, but it's in a 'fail'
state.

So right after the 'while' loop, write:

inGameFile.clea r();
//exit(1);
If you want to use exit(), you'll need to provide its
declaration (#include <cstdlib> or <stdlib.h>
I recommend you don't use 'exit()' though, because
destructors will not be called. I recommend

return EXIT_FAILURE; // needs #include <stdlib.h> or <cstdlib>
}

cout << inGameFile.tell g() << endl; // result is -1
inGameFile.seek g( 0, ios::beg );
cout << inGameFile.tell g() << endl; // result is -1 again!
Every attempt at i/o will fail until the stream state
is reset (e.g. with 'clear()'.

// Does not work this way; try to close and reopen:
inGameFile.clos e();
if ( !inGameFile)
{
cerr << "Failed to close(3).\n";
//exit(1);
}

inGameFile.open ( "scores.txt ", ios::in );
if ( !inGameFile)
{
cerr << "Failed to open(4).\n";
//exit(1);
} inGameFile.open ( "scores.txt ", ios::in );

}
I think the 'cleaner' way is to close and reopen
rather than use 'seekg()'.

############### #############

The output is:

A total of 1363 games played.
No longer open(2).
-1
-1
Failed to close(3).
Failed to open(4).

############### #############

Compiler is c++ (GCC) 3.2.2 20030222 (Red Hat Linux 3.2.2-5)

I did something similar on gnu c++ 2.95 under windows, where I could
resolve it by closing and reopening the file. This time it does not
work.

It seems that my inGameFile is automatically closed
No it is not. It will not be closed until you either
explicitly call 'close()', or the stream object goes
out of scope.
when I read the
last line, and I can neither move the get pointer nor re-open the
file.
You can't do *anything* until you reset the stream state.

Can someone explain me how can I overcome this?


See above.

-Mike
Jul 19 '05 #2
Sanyi wrote in news:e3******** *************** ***@posting.goo gle.com:

// count the number of games
int nGames = 0;
while ( inGameFile.getl ine(stLine, LINE) )
{
nGames++;
}
When this loop exits the stream is in an "fail" state as the last
operation .getline(...) failed, you need to clear this error
before proceding:

inGameFile.clea r();

You might also want to check that the op "failed" for the right
reason first, ie EOF was encounterd:

// the loop exited why?
if ( !inGameFile.eof () )
{
cerr << "read of game file failed\n";
exit( 0 );
}

// Ok to clear EOF was expected:
inGameFile.clea r();
cout << "A total of " << nGames << " games played.\n";
// Everything works fine this far

if ( !inGameFile)
{
cerr << "No longer open(2).\n"; // inGameFile no longer defined!
//exit(1);
}


HTH

Rob.
--
http://www.victim-prime.dsl.pipex.com/
Jul 19 '05 #3
"Mike Wahler" <mk******@mkwah ler.net> wrote in message
news:Hp******** *********@newsr ead3.news.pas.e arthlink.net...

<< Message Stripped >>
inGameFile.open ( "scores.txt ", ios::in );
if ( !inGameFile)
{
cerr << "Failed to open(4).\n";
//exit(1);
} inGameFile.open ( "scores.txt ", ios::in );

}
I think the 'cleaner' way is to close and reopen
rather than use 'seekg()'.


I don't understand the reason for not using seekg() function. Closing &
re-opening a file is more expensive operation than setting the seek pointer.
Setting a pointer is normally not an unclean operation.

############### #############

The output is:

A total of 1363 games played.
No longer open(2).
-1
-1
Failed to close(3).
Failed to open(4).


Jul 19 '05 #4
"Mohamed Ghouse" <gh****@emanate .info> wrote in message
news:10******** *******@ernani. logica.co.uk...
"Mike Wahler" <mk******@mkwah ler.net> wrote in message
news:Hp******** *********@newsr ead3.news.pas.e arthlink.net...
I think the 'cleaner' way is to close and reopen
rather than use 'seekg()'.
I don't understand the reason for not using seekg() function. Closing &
re-opening a file is more expensive operation than setting the seek

pointer.

You cannot know that for sure, this depends upon
the host platform. The "traditiona l wisdom" is
to not worry about performance while writing the
code, but only after its been *proven* (via testing
and profiling) to be an issue.
Setting a pointer is normally not an unclean operation.


I meant 'clean' from a source code perspective.
Of course this is only my opinion. Using "seek"
operation isn't technically "right" or "wrong".

-Mike
Jul 19 '05 #5
WW
Mike Wahler wrote:
I think the 'cleaner' way is to close and reopen
rather than use 'seekg()'.


Except for platforms where closing the last file on a media enables the
media to be ejected, and if there is a waiting eject request it will be
ejected. So I say if you want to read the file from the beginning go to the
beginning and read it. If you want to close it, close it. Just like I do
not buy a book again because I want to read it again. :-) But this is only
my experience and opinion.

--
WW aka Attila
Jul 19 '05 #6

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

Similar topics

6
10333
by: Christopher Brandsdal | last post by:
Hi! I get an error when I run my code Is there any other way to get te information from my form? Heres the error I get and the code beneath. Line 120 is market with ''''''''''''Line 120''''''''''''''''''''' ''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
7
4536
by: Joe | last post by:
I have an upload file operation in the web application. UploadForm.asp is the form, and UploadAction.asp is the form processing. //UploadForm.asp <FORM NAME="InputForm" ACTION="UploadAction.asp" METHOD="POST" enctype=multipart/form-data> <input type="file" name="fileName"> //etc ... </FORM>
8
5476
by: baustin75 | last post by:
Posted: Mon Oct 03, 2005 1:41 pm Post subject: cannot mail() in ie only when debugging in php designer 2005 -------------------------------------------------------------------------------- Hello, I have a very simple problem but cannot seem to figure it out. I have a very simple php script that sends a test email to myself. When I debug it in PHP designer, it works with no problems, I get the test email. If
10
4466
by: Jean-David Beyer | last post by:
I have some programs running on Red Hat Linux 7.3 working with IBM DB2 V6.1 (with all the FixPacks) on my old machine. I have just installed IBM DB2 V8.1 on this (new) machine running Red Hat Enterplise Linux 3 ES, and applied FixPack fp5_mi00069.tar to it. After creating an instance, starting the database, creating a database, and entering the table definitions, all of which seems to work OK, I entered a tiny 8-row table and can do...
6
13727
by: Chad Crowder | last post by:
Getting the following error on my production server whether the file exists or not: "System.IO.IOException: Cannot create a file when that file already exists." Here's the code generating the error (seems to be happening when I try creating a directory) If dirmgr.Exists("s:\blah\" & txt_name.Text) Then lblerror.Text = lblerror.Text & "Unable to build physical path. " &
9
2428
by: ypjofficial | last post by:
Hello All, I am defining a class with one virtual function and storing its first 4 bytes ie. the address of the virtual function table to a file.I am again rereading the file in the same program and calling the virtual function.The function gets called nicely but it shows the junk values for the member variables of the class of which the function is a member..below is the code //Program start #include "iostream.h"
0
2811
by: =?Utf-8?B?QWxoYW1icmEgRWlkb3MgS2lxdWVuZXQ=?= | last post by:
Hello, mister I have an application web asp.net 2.0 + vs 2005 and VS 2005 Web Application Project. Its appears this error in execution: "Cannot Create/Shadow Copy '<projectname>' when that file arleady exists" error.
1
4688
by: kw.housing | last post by:
I have all the library already in path: $ ls -l /opt/IBM/db2/lib64 | grep libdb2o -r-xr-xr-x 1 bin bin 7757295 Jul 12 2006 libdb2osse.a* -r--r--r-- 1 bin bin 227313 Jul 12 2006 libdb2osse_db2.a $ env | grep LIBPATH LIBPATH=/opt/IBM/db2/lib64:/home/perfpol2/sqllib/lib64:/usr/lib:/lib However, when I call db2imigr, I still get the following error, what can be
4
11237
by: danomano | last post by:
The code below works fine. As of now I just set the buffer length real big and all is good. However, I hate the impreciseness of that. So my question in general is how do I know what length to set the buffer? In specific, my question is what causes the 'completed' event in the OnSocketConnectCompleted method to fire? Does it fire at end of a packet or does happen at some end of data marker? public SocketClient(Page pg, Int32...
0
8823
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...
1
9104
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
9047
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
6646
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
5967
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4477
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 the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4738
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3175
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
3
2119
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.