Page 1 of 2 12 Last
  • Jump to page:
    #1
  1. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Mar 2005
    Posts
    52
    Rep Power
    10

    Unhappy C++ ifstream can't open file


    i've got a function in a class which opens a text file and reads the text from it.problem is that it won't open the actually file but me and my friend can't see anything wrong with it! i've followed the turorials on how to do it,but still doesn't work

    Code:
    void CHighScore::ReadScores()
    {	
    	const char * filename = "\\extras\\HighScores.txt";
    	ifstream scores;
    	scores.open(filename,ios::in);
    	if (! scores.is_open()) {
    		MessageBox(NULL, "Error opening file!", "File Error!",
    				     MB_ICONEXCLAMATION | MB_OK);
    	}
    	else {
    		int a = 0;
    		while (scores >> name >> score) {
    			HighScore[a] = score;
    			ScorerName[a] = name;
    			a++;
    		}
    
    		scores.close();
    	}
    
    }
    the text file im reading from containts the following information :

    Code:
    samana 70000
    Bob 800
    Jim 500
    James 300
    Steven 100
  2. #2
  3. I'm Baaaaaaack!
    Devshed God 1st Plane (5500 - 5999 posts)

    Join Date
    Jul 2003
    Location
    Maryland
    Posts
    5,538
    Rep Power
    243
    This worked fine for me:

    Code:
    #include <fstream>
    #include <iostream>
    #include <string>
    
    using namespace std;
    
    void ReadScores() {
        const char * filename = "HighScores.txt";
        ifstream scores;
        string name;
        int score;
    
        scores.open(filename,ios::in);
        if (!scores.is_open()) {
            cerr << "Can't open " << filename << "!\n";
        }else {
            int a = 0;
            while (scores >> name >> score) {
                cout << name << "\t" << score << endl;
            }
            scores.close();
        }
    }
    
    int main(){
        ReadScores();
        return 0;
    }

    My blog, The Fount of Useless Information http://sol-biotech.com/wordpress/
    Free code: http://sol-biotech.com/code/.
    Secure Programming: http://sol-biotech.com/code/SecProgFAQ.html.
    Performance Programming: http://sol-biotech.com/code/PerformanceProgramming.html.
    LinkedIn Profile: http://www.linkedin.com/in/keithoxenrider

    It is not that old programmers are any smarter or code better, it is just that they have made the same stupid mistake so many times that it is second nature to fix it.
    --Me, I just made it up

    The reasonable man adapts himself to the world; the unreasonable one persists in trying to adapt the world to himself. Therefore, all progress depends on the unreasonable man.
    --George Bernard Shaw
  4. #3
  5. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Mar 2005
    Posts
    52
    Rep Power
    10
    so there's nothing wrong with it!?
  6. #4
  7. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Mar 2005
    Posts
    52
    Rep Power
    10
    Originally Posted by mitakeet
    This worked fine for me:

    Code:
    #include <fstream>
    #include <iostream>
    #include <string>
    
    using namespace std;
    
    void ReadScores() {
        const char * filename = "HighScores.txt";
        ifstream scores;
        string name;
        int score;
    
        scores.open(filename,ios::in);
        if (!scores.is_open()) {
            cerr << "Can't open " << filename << "!\n";
        }else {
            int a = 0;
            while (scores >> name >> score) {
                cout << name << "\t" << score << endl;
            }
            scores.close();
        }
    }
    
    int main(){
        ReadScores();
        return 0;
    }
    i've tried the same code as what you used, in a new application to test it,but it can't open the file either?
  8. #5
  9. I'm Baaaaaaack!
    Devshed God 1st Plane (5500 - 5999 posts)

    Join Date
    Jul 2003
    Location
    Maryland
    Posts
    5,538
    Rep Power
    243
    The file must exist at the location given (in my example the directory in which the program is executed) AND the application must have permissions to open the file.

    My blog, The Fount of Useless Information http://sol-biotech.com/wordpress/
    Free code: http://sol-biotech.com/code/.
    Secure Programming: http://sol-biotech.com/code/SecProgFAQ.html.
    Performance Programming: http://sol-biotech.com/code/PerformanceProgramming.html.
    LinkedIn Profile: http://www.linkedin.com/in/keithoxenrider

    It is not that old programmers are any smarter or code better, it is just that they have made the same stupid mistake so many times that it is second nature to fix it.
    --Me, I just made it up

    The reasonable man adapts himself to the world; the unreasonable one persists in trying to adapt the world to himself. Therefore, all progress depends on the unreasonable man.
    --George Bernard Shaw
  10. #6
  11. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Mar 2005
    Posts
    52
    Rep Power
    10
    Originally Posted by mitakeet
    The file must exist at the location given (in my example the directory in which the program is executed) AND the application must have permissions to open the file.
    how do i give the application permission to open the file?
  12. #7
  13. Left due to despotic ad-min
    Devshed Beginner (1000 - 1499 posts)

    Join Date
    Jun 2003
    Posts
    1,044
    Rep Power
    14
    Assuming the file is not somehow inaccessible, my guess is that the file is located somewhere different from where you're telling your program to look for it.

    The file named "\\extras\\HighScores.txt" is in an absolute location: it will be in the location C:\extras\HighScores.txt if the program (or it's working directory) is on the C drive.

    If you intend the extras directory to be relative to the path where the executable is (for example, the program might be in "C:\\Program Files\\YourProgram", and the text file is in "C:\\Program Files\\YourProgram\\extras\\HighScore.txt", take off the leading "\\". That turns the filename into a relative path rather than an absolute one.
    It is only our bad temper that we put down to being tired or worried or hungry; we put our good temper down to ourselves."
    -- C.S. Lewis

    I like long walks, especially when they're taken by people who annoy me.
    --Fred Allen
  14. #8
  15. I'm Baaaaaaack!
    Devshed God 1st Plane (5500 - 5999 posts)

    Join Date
    Jul 2003
    Location
    Maryland
    Posts
    5,538
    Rep Power
    243
    If you are the person running the application and you have permissions to read the file, then the app has permissions to read the file. I suspect it is a file location problem and you are just focusing on the wrong thing. If you can't see the file in the same directory as my test application then you should not expect it to work!

    My blog, The Fount of Useless Information http://sol-biotech.com/wordpress/
    Free code: http://sol-biotech.com/code/.
    Secure Programming: http://sol-biotech.com/code/SecProgFAQ.html.
    Performance Programming: http://sol-biotech.com/code/PerformanceProgramming.html.
    LinkedIn Profile: http://www.linkedin.com/in/keithoxenrider

    It is not that old programmers are any smarter or code better, it is just that they have made the same stupid mistake so many times that it is second nature to fix it.
    --Me, I just made it up

    The reasonable man adapts himself to the world; the unreasonable one persists in trying to adapt the world to himself. Therefore, all progress depends on the unreasonable man.
    --George Bernard Shaw
  16. #9
  17. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Mar 2005
    Posts
    52
    Rep Power
    10
    Originally Posted by grumpy
    Assuming the file is not somehow inaccessible, my guess is that the file is located somewhere different from where you're telling your program to look for it.

    The file named "\\extras\\HighScores.txt" is in an absolute location: it will be in the location C:\extras\HighScores.txt if the program (or it's working directory) is on the C drive.

    If you intend the extras directory to be relative to the path where the executable is (for example, the program might be in "C:\\Program Files\\YourProgram", and the text file is in "C:\\Program Files\\YourProgram\\extras\\HighScore.txt", take off the leading "\\". That turns the filename into a relative path rather than an absolute one.
    thats 1 thinkg i was doing wrong,so i've changed it to "extras\\HighScores.txt",but still doesn't work

    mitakeet...i created a new txt document and put it in the same folder as your test.still couldn't open it though
  18. #10
  19. I'm Baaaaaaack!
    Devshed God 1st Plane (5500 - 5999 posts)

    Join Date
    Jul 2003
    Location
    Maryland
    Posts
    5,538
    Rep Power
    243
    Then you either had copy and paste problems, missspelled the text file or are running the program in the wrong location. I highly doubt it is something more complex than that (and REALLY doubt it is a permissions problem), you just need to take a break, get some fresh air and maybe a bite to eat, then starting in a completely fresh directory try my example code (with a clean copy and paste) and see what happens.

    My blog, The Fount of Useless Information http://sol-biotech.com/wordpress/
    Free code: http://sol-biotech.com/code/.
    Secure Programming: http://sol-biotech.com/code/SecProgFAQ.html.
    Performance Programming: http://sol-biotech.com/code/PerformanceProgramming.html.
    LinkedIn Profile: http://www.linkedin.com/in/keithoxenrider

    It is not that old programmers are any smarter or code better, it is just that they have made the same stupid mistake so many times that it is second nature to fix it.
    --Me, I just made it up

    The reasonable man adapts himself to the world; the unreasonable one persists in trying to adapt the world to himself. Therefore, all progress depends on the unreasonable man.
    --George Bernard Shaw
  20. #11
  21. No Profile Picture
    cien por ciento conejo.
    Devshed Newbie (0 - 499 posts)

    Join Date
    Apr 2004
    Posts
    411
    Rep Power
    11
    try running the following code:

    Code:
    #include <fstream>
    #include <iostream>
    #include <string>
    
    using namespace std;
    
    void WriteScores(const string & fname)
    {
      ofstream output;
      output.open(fname.c_str(), ios::out);
      if(output)
        {
          cout<<"creating scores..."<<flush;
          output<<"samana"<<'\t'<<"70000\n"
    	    <<"Bob"<<'\t'<<"800\n"
    	    <<"Jim"<<'\t'<<"500\n"
    	    <<"James"<<'\t'<<"300\n"
    	    <<"Steven"<<'\t'<<"100\n";
          output.flush();
          output.close();
          cout<<"done"<<endl;
        }
      else{
        cout<<"scores file creation failed for file "<<fname<<endl;
      }
    
    }
    
    
    void ReadScores(const string & filename) {
      //    const char * filename = "HighScores.txt";
        ifstream scores;
        string name;
        int score;
    
        scores.open(filename.c_str(),ios::in);
        if (!scores.is_open()) {
            cerr << "Can't open " << filename << "!\n";
        }else {
            int a = 0;
            while (scores >> name >> score) {
    	  a++;
    	  cout<<a<<'\t'<< name << "\t" << score << endl;
            }
            scores.close();
        }
    }
    
    int main(){
      string TestFName("test.txt");
      WriteScores(TestFName);
      ReadScores(TestFName);
      return 0;
    }
    you should see the following regardless of you cwd:

    PHP Code:
    [matt@conejito inout]$ g++ -Wall -ansi -pedantic test.cc
    [matt@conejito inout]$ ./a.out
    creating scores
    ...done
    1       samana  70000
    2       Bob     800
    3       Jim     500
    4       James   300
    5       Steven  100
    [matt@conejito inout]$ 
  22. #12
  23. Left due to despotic ad-min
    Devshed Beginner (1000 - 1499 posts)

    Join Date
    Jun 2003
    Posts
    1,044
    Rep Power
    14
    Things to check:

    1) What is the full name of the file? In particular, are there in spaces in it, which are not present in the filename in your code? Is the name exactly the same (eg the name in your code has the same mix of upper and lower case letters)? Does it have a .txt extension? Is it possible you made a typo when saving the file (one thing I've done occasionally with notepad is create a file named x.txt.txt when I intended to create x.txt).

    2) What is the full path name of the executable (i.e. what disk, what path, etc)?

    3) What is the full path in which the file is located?

    4) Does another program (eg a text editor) have the file open? If so, that may prevent you opening it again.

    5) If you're running the program in an IDE (eg stepping through it to debug), the actual working directory may be different from where your data file is.
    It is only our bad temper that we put down to being tired or worried or hungry; we put our good temper down to ourselves."
    -- C.S. Lewis

    I like long walks, especially when they're taken by people who annoy me.
    --Fred Allen
  24. #13
  25. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Mar 2005
    Posts
    52
    Rep Power
    10
    woohoo,finally sussed it!! it was the end of the file (.txt).when i created the file i just right clicked,selected text document,then entered HighScores.txt as the filename.obviously that means the text file was actually named HighScores.txt.txt like grumpy said :) i only noticed it by comparing 2 different file names!

    thanks for your help guys/girls as my code works a treat!! :)
  26. #14
  27. No Profile Picture
    Contributing User
    Devshed Novice (500 - 999 posts)

    Join Date
    May 2004
    Location
    Adelaide, Australia
    Posts
    880
    Rep Power
    11
    Switch off that damned "hide known extensions" option in Windows
    From file explorer, go tools->folder options->view about 9 options down in Windows XP.
    I think the default value for this setting is the sole cause for people clicking on most email viruses/trojan programs.

    Comments on this post

    • nnxion agrees : Yup, first thing I turn off when installing Windows :D.
  28. #15
  29. I'm Baaaaaaack!
    Devshed God 1st Plane (5500 - 5999 posts)

    Join Date
    Jul 2003
    Location
    Maryland
    Posts
    5,538
    Rep Power
    243
    Isn't it great how the OS blocks you from getting things done?

    My blog, The Fount of Useless Information http://sol-biotech.com/wordpress/
    Free code: http://sol-biotech.com/code/.
    Secure Programming: http://sol-biotech.com/code/SecProgFAQ.html.
    Performance Programming: http://sol-biotech.com/code/PerformanceProgramming.html.
    LinkedIn Profile: http://www.linkedin.com/in/keithoxenrider

    It is not that old programmers are any smarter or code better, it is just that they have made the same stupid mistake so many times that it is second nature to fix it.
    --Me, I just made it up

    The reasonable man adapts himself to the world; the unreasonable one persists in trying to adapt the world to himself. Therefore, all progress depends on the unreasonable man.
    --George Bernard Shaw
Page 1 of 2 12 Last
  • Jump to page:

IMN logo majestic logo threadwatch logo seochat tools logo