Program not opening file

Hi, I'm having some difficulties with my code

The function is supposed to ask the user for the file name and open the file, but it keeps failing to open the file and stays in the while loop even if the name of the file is entered correctly.


1
2
3
4
5
6
7
8
9
10
11
	ifstream input;
	string fileName = ("randomname.txt");

	input.open(fileName);
	
    while (input.fail())
    {
    cout << "Enter file name:" ;
    cin >> fileName;
    input.open(fileName);
    }


Thanks for any help!
Last edited on
What platform, IDE, and compiler are you using? Are you sure that the working directory of the program you are executing is the same as the location of randomname.txt?

For example, depending on how you have your project set up, your working directory might be MyProject/, but the actual executable file is in MyProject/bin/Debug/. Check your project settings to make sure your file is in the proper directory.
You should always write the location of the file you want to open. Like string filePath = "D:\\somewhere\\somewhere\\" and string fileName = "myfile.txt". The open it with filePath+fileName
I disagree with that, at least for any program that wants the ability to be portable. Hardcoding a drive and an absolute file path would make that impossible. But I agree it would temporarily help the OP with their current problem. Also, C++ does not require backslash '\\' even if running in Windows. You can use normal, [forward] slashes, "D:/foo/fab".

Also, on Windows, you can do system("cd"); to print out the current absolute file path, and system("pwd"); on Linux. (Note this is only to test your current directory, I do not suggest using system calls for an actual, end-product program).
Last edited on
Topic archived. No new replies allowed.