Thread: Cant open file

  1. #1
    Registered User
    Join Date
    Feb 2011
    Location
    Norway
    Posts
    5

    Cant open file

    Hey, im trying to open my file but it dosent work, what is wrong?
    Ive created a file called "tallfil.dat" and it contains some numbers. It lies under the same path as the c++ file.

    Code:
    #include <fstream> //Må inkluderes for å jobbe med datafiler
    #include <iostream>
    #include <cstdlib>
    #include <string>
    
    using namespace std;
    
    const string filnavn = "tallfil.dat";
    
    int main()
    {
    	ifstream innfil;
    	innfil.open(filnavn.c_str());
    	if(!innfil)
    	{
    		cout << "Feil ved aapning av innfil" << endl;
    		exit(EXIT_FAILURE);
    	}
    
    	int tall;
    	int sum = 0;
    	innfil >> tall;
    	while(tall > 0)
    	{
    		sum += tall;
    		innfil >> tall;
    	}
    
    	cout << "Summen er " << sum << endl;
    	innfil.close();
    
    	return 0;
    	
    }

  2. #2
    Registered User
    Join Date
    Aug 2010
    Location
    Poland
    Posts
    733
    It must be located in the same directory as the executable.
    And what "doesn't work"?

  3. #3
    Registered User
    Join Date
    Apr 2011
    Posts
    13
    try putting it in your debug folder?

  4. #4
    C++ Junkie Mozza314's Avatar
    Join Date
    Jan 2011
    Location
    Australia
    Posts
    174
    What does your tallfil.dat file look like? The first time I tested your code the program was stuck in an infinite loop because there was no 0 or negative value in the file to terminate that while loop.

    Also, what specifically is the problem you're having? Please avoid being so general as "it doesn't work". What happens when you try it?

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Problem reading from file stream
    By shmitson in forum C Programming
    Replies: 0
    Last Post: 04-05-2011, 04:37 PM
  2. Free glut, Rastering a .raw file
    By Falconmick in forum C Programming
    Replies: 3
    Last Post: 04-03-2011, 04:41 AM
  3. Need Help Fixing My C Program. Deals with File I/O
    By Matus in forum C Programming
    Replies: 7
    Last Post: 04-29-2008, 07:51 PM
  4. Encryption program
    By zeiffelz in forum C Programming
    Replies: 1
    Last Post: 06-15-2005, 03:39 AM