473,385 Members | 1,813 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,385 software developers and data experts.

ifstream errors

So... I'm trying to get used to using C++ ifstream (or ofstream)
instead of stdio (although I'm having second thoughts). Anyways, I
want to be able to display a meaningful error message if ifstream
fails to open a file, but nothing I read about ifstream says anything
about a reliable place to get an error message. Using stdio I can
simply do:

FILE *f = fopen(filename, "rb");
if (!f)
perror(filename);

So far the best I've been able to do using ifstream is:

ifstream f(filename, ios_base::in | ios_base::binary);
if (!f.is_open())
cerr << filename << ": tough luck!" << endl;

What is a reliable way to get a real error message? Even the example
at cplusplus.com:

http://www.cplusplus.com/reference/i...m/is_open.html

Gives a crappy error message.

Thanks,
AJ
Mar 27 '08 #1
11 8081
On Mar 27, 4:29 am, adramo...@gmail.com wrote:
What is a reliable way to get a real error message?
Oh, also, related to this, how do I tell if >fails? Say I am reading
4 integers from an ifstream opened in text mode. Using stdio:

int a, b, c, d;
if (fscanf(infile, "%i%i%i%i", &a, &b, &c, &d) != 4)
fprintf(stderr, "error parsing line\n");

But using ifstream:

int a, b, c, d;
infile << a << b << c << d;
// how to check for failure...?
Thanks
Mar 27 '08 #2
On Mar 27, 4:33 am, adramo...@gmail.com wrote:
infile << a << b << c << d;

That is, >>
Mar 27 '08 #3
On 27 Mrz., 09:33, adramo...@gmail.com wrote:
[..]
But using ifstream:

int a, b, c, d;
infile << a << b << c << d;
// how to check for failure...?
if ( infile.fail() ) {
....
}

best,

Michael
Mar 27 '08 #4
On Mar 27, 9:29 am, adramo...@gmail.com wrote:
So... I'm trying to get used to using C++ ifstream (or
ofstream) instead of stdio (although I'm having second
thoughts). Anyways, I want to be able to display a meaningful
error message if ifstream fails to open a file, but nothing I
read about ifstream says anything about a reliable place to
get an error message. Using stdio I can simply do:
FILE *f = fopen(filename, "rb");
if (!f)
perror(filename);
Whether that gives you something meaningfull or not depends
somewhat on the implementation. What perror outputs depends on
errno, and the standard really doesn't specify too much in this
regard.
So far the best I've been able to do using ifstream is:
ifstream f(filename, ios_base::in | ios_base::binary);
if (!f.is_open())
cerr << filename << ": tough luck!" << endl;
Why not?

ifstream f(filename, ios_base::in | ios_base::binary);
if (!f.is_open())
perror( filename ) ;

You're very much in the domain of implementation defined, or
even unspecified, both with FILE* and ifstream, but in general,
I'd expect both of them to behave more or less identically here.
(Under Unix, I'm pretty sure they will; errno is set by the
functions in the system API which ifstream or fopen must call.
They seem to behave the same under Windows as well, at least
with VC++.)

--
James Kanze (GABI Software) email:ja*********@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientierter Datenverarbeitung
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34
Mar 27 '08 #5
On Mar 27, 9:33 am, adramo...@gmail.com wrote:

[...]
int a, b, c, d;
if (fscanf(infile, "%i%i%i%i", &a, &b, &c, &d) != 4)
fprintf(stderr, "error parsing line\n");
But using ifstream:
int a, b, c, d;
infile << a << b << c << d;
// how to check for failure...?
if ( ! infile ) ...

You can use an istream as a boolean; it will behave as true if
no error has occured, and as false once an error has been seen.
Once you've detected an error (and only then), you can use more
specific functions to determine the cause:

if ( ! infile ) {
if ( infile.bad() ) {
// Serious hardware problem... (read error, etc.)
// A lot of implementations aren't too rigorous
// about reporting this, and you might never see
// it.
} else if ( ! infile.eof() ) {
// Format error in the input stream.
} else {
// Probably an end of file (although in a few rare
// cases, infile.eof() can return true even though
// there was a format error in the input).
}
}

The error condition is sticky: it must be cleared (function
istream::clear()) before you can read further (or do anything
else) with the stream.

A typical idiom for reading files is:

while ( infile >a >b >c ) {
// ...
}

or (more often, because it allows better recovery in case of a
format error):

std::string line ;
while ( std::getline( infile, line ) ) {
std::istringstream parse( line ) ;
parse >a >b >c >d >std::ws ;
if ( ! parse || parse.peek() != EOF ) {
// Syntax error in the line...
} else {
// ...
}
}

This has the advantage of not putting the main input in an error
state, and leaving it correctly positionned for further reading
in case of an error. (Like fscanf, the >operators treat a new
line as white space. So if the input syntax is line oriented,
you probably want to use getline to read it, and istringstream
to parse each line. Something like you'd use fgets to read and
sscanf to parse in C, except that it doesn't require any special
handling for excessively long lines.)

--
James Kanze (GABI Software) email:ja*********@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientierter Datenverarbeitung
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34
Mar 27 '08 #6
ad*******@gmail.com wrote:
On Mar 27, 4:29 am, adramo...@gmail.com wrote:
>What is a reliable way to get a real error message?

Oh, also, related to this, how do I tell if >fails? Say I am reading
4 integers from an ifstream opened in text mode. Using stdio:

int a, b, c, d;
if (fscanf(infile, "%i%i%i%i", &a, &b, &c, &d) != 4)
fprintf(stderr, "error parsing line\n");

But using ifstream:

int a, b, c, d;
infile << a << b << c << d;
// how to check for failure...?
Thanks
if ( infile >a >b >c >d )
// success
else
// failure

Alternately

if ( ! ( infile >a >b >c >d ) )
// failure
else
// success
--
Jim Langston
ta*******@rocketmail.com
Mar 27 '08 #7
ad*******@gmail.com wrote:
>
FILE *f = fopen(filename, "rb");
if (!f)
perror(filename);
If your machine has perror, it probably has strerror
which returns a char* with the same content.
Mar 27 '08 #8
On Mar 27, 7:57 am, Ron Natalie <r...@spamcop.netwrote:
adramo...@gmail.com wrote:
FILE *f = fopen(filename, "rb");
if (!f)
perror(filename);

If your machine has perror, it probably has strerror
which returns a char* with the same content.
Thanks for your reply. Mostly what I was wondering about was if
ifstream sets errno.
Mar 27 '08 #9
On Mar 27, 4:53 am, Abhishek Padmanabh <abhishek.padman...@gmail.com>
wrote:
Using member operator! to test file open failure might make it look
easier.
Hey cool, thanks for the tip.
Failures with fstream objects are notified by setting the following
bits: eofbit, failbit and badbit. So, if you want granularity in
reporting errors, you would need to check them individually.
I see; this makes sense. It should be enough... mostly I'd like to be
able to notify the user about things like "file not found" as opposed
to "permission denied", though. Well I guess really those are the two
big errors. In the end it's not critical, it's just something I was
wondering about.

Thanks again, that helps a lot
AJ
Mar 27 '08 #10
On Mar 27, 6:24 am, James Kanze <james.ka...@gmail.comwrote:
[a great reply]
Thanks a lot! That clears a lot of stuff up. The istringstream is
pretty cool, I was wondering if there was something like that.

I have one small new question left: Do istreams have anything like
scanf's %[] for matching only characters in a set (I think of it like
the poor man's regular expression)? It's something I've found pretty
handy sometimes in the past.

Thanks again,
AJ
Mar 27 '08 #11
On Mar 27, 1:46 pm, adramo...@gmail.com wrote:
On Mar 27, 6:24 am, James Kanze <james.ka...@gmail.comwrote:
I have one small new question left: Do istreams have anything
like scanf's %[] for matching only characters in a set (I
think of it like the poor man's regular expression)? It's
something I've found pretty handy sometimes in the past.
No, but unlike scanf, it's totally extensible. I don't think
I've ever written an application where we didn't have some user
defined extractors or manipulators. Often, too, I'll use
something more or less like a decorator (it is a decorator,
vis-a-vis iostream), to control input or output in some special
way. Just write an extractor which operates indirectly on your
string.

Alternatively, you don't necessarily need a poor man's
replacement. Boost regular expressions works very well, and is
in the process of being adopted into the standard.

--
James Kanze (GABI Software) email:ja*********@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientierter Datenverarbeitung
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34
Mar 27 '08 #12

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

Similar topics

2
by: Dave Johnston | last post by:
Hi, I'm currently trying to create a wrapper that uses C functions but behaves like ifstream (from fstream.h) - this is because the platform I'm using (WinCE) doesn't support streams and this is...
6
by: Herv? LEBAIL | last post by:
Hi everybody, I'm writing a program which use the <string>, <vector> and <ifstream> classes. Given an array of string, i.e vector<string> file_names, example : file_names = "file1.txt"...
6
by: Ram Laxman | last post by:
Iam new bie to C++ programming.. I want to write a program which will read the Comma separated values(CSV) file column wise. For example: In a.txt: "TicketNumber","Phone","CarNumber"...
6
by: csvka | last post by:
Hello, I wonder if I could pick your brains. I'm beginning to learn about C++. I have opened a file in my program and I want to read lines from it. I would like this to be done in a separate...
4
by: hall | last post by:
Hi. I ran across a bug in one of my problems and after spending some time tracking it down i found that the problem arose in a piece of code that essentially did this: ----------- ifstream...
10
by: sam | last post by:
Hi, Can anyone tell me how to print a file name from ifstream? the following cout code does not print the filename I created with ifstream preivous: ifstream is; is.open ("text.txt");
0
by: rocketdodger | last post by:
something happened to my program and now any time i try to open a file it crashes I'm not talking about a failure to open, or any errors, I mean a total lockup. I use windows xp and compile with...
4
by: marathoner | last post by:
I tried your advice, and replaced "ifstream" with "std::ifstream". I also replaced instances of "ofstream" with "std::ofstream". Those syntax errors were resolved. When I added "std" to the...
0
by: James Kanze | last post by:
On 11 avr, 17:44, "mc" <mc_r...@yahoo.comwrote: OK. If the actual format is well documented, that's half the battle won already. Note, however, that reading a float as an int is still very...
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: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
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: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
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,...
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...

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.