Problem opening file

I cannot for the life of me figure out why this file will not open up and be processes like it should. The file is located in the same directory as the .cpp file, but it still doesn't work. I keep on getting "Unable to open file"

Any ideas?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include <iostream>
#include <iomanip>
#include <fstream>
using namespace std;

int main() {
    int sum = 0;
    int x;
    ifstream inFile;
    
    inFile.open("3.txt");
    if (!inFile) {
        cout << "Unable to open file";
        system("pause");
        exit(1); // terminate with error
    }
    
    while (inFile >> x) {
        sum = sum + x;
    }
    
    inFile.close();
    cout << "Sum = " << sum << endl; 
    system("pause");
    return 0;
}
The file is located in the same directory as the .cpp file


This may or may not be the right directory. Some IDEs get weird with what directory is the current directory when you run the program.

One way to test is to print the current directory. Assuming you're on Windows:

1
2
3
4
5
6
7
8
9
#include <windows.h>

int main()
{
  char curdirectory[MAX_PATH];
  GetCurrentDirectoryA(MAX_PATH,curdirectory);
  cout << curdirectory;

  //... 


That will let you know the current directory. That is the dir your file needs to be in.
Ok I did that and this is what I changed it to. I am still getting the same error though.

This is what I got from your code: C:\Dev-Cpp\Homework

inFile.open("3.txt");
Last edited on
OMG. The file in windows was 3.txt.txt

So that is the reason why it was not opening. I don't understand why windows would even allow that in the first place.
Topic archived. No new replies allowed.