By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
446,406 Members | 982 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 446,406 IT Pros & Developers. It's quick & easy.

ifstream always fails

P: 6
Hello all, I need a little help with this. I can't seem to get ifstream ( or fstream ) to read anything.
In the code:
Expand|Select|Wrap|Line Numbers
  1. ifstream input = NULL;
  2.     input.open("tester.txt");
  3.     if(input.bad())
  4.     {
  5.         cout << "Bad input." << endl;
  6.         return -2;
  7.     }
  8.     if(input.fail())
  9.     {
  10.         cout << "Open failed." << endl;
  11.         return -1;
  12.     }
  13.     return 0;
  14.  
the fail() code always executes. "tester.txt" is in the same directory as the program source code. I'm using VC++ 6.0.
Sep 27 '06 #1
Share this Question
Share on Google+
5 Replies


P: 59
try this:

Expand|Select|Wrap|Line Numbers
  1.     ifstream fin("program2.txt");
  2.         if (!fin) 
  3.          cerr << "error opening stream";
  4.  
make sure you include

#include <iostream>
Sep 27 '06 #2

P: 6
Nope.

Expand|Select|Wrap|Line Numbers
  1. ifstream fin("tester.txt");
  2.     char * input = NULL;
  3.     int k;
  4.     if (!fin) 
  5.         {
  6.          cerr << "error opening stream";
  7.         }
  8.     fin >> input;
  9.     fin >> k;
  10.     cout << input << " " << k << endl;
  11.     fin.close();
  12.     return 0;
Gives me a lovely little access violation. I can't figure out what's causing that.
Sep 27 '06 #3

Banfa
Expert Mod 5K+
P: 8,916
You are passing it a string pointer (input) so it is writing a line of data to the location pointed to by input.

Unfortunately instead of point input at any data you have made it a NULL pointer. You need to allocate some data to input.
Sep 27 '06 #4

100+
P: 293
D_C
I use Dev-C++ and I noticed that every time I run the application from Dev-C++, file I/O does not work. However, if I go find where *.exe is located, and run it from there, it works fine.
Sep 27 '06 #5

P: 59
also, make sure your file is not in "read only" mode. lol
Sep 28 '06 #6

Post your reply

Sign in to post your reply or Sign up for a free account.