Having trouble opening file c++

closed account (i8bjz8AR)
Hi guys, I wrote this program to open a file. However now, when build and run, i don't get any errors. But the file wont open. i have created a folder with the file in the same location as where this program is saved. From what I have read, it has something with the directory not being in the correct location. Any help would be greatly appreciated!
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
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
  #include<iostream>
#include<fstream>
#include<string>
using namespace std;

int main()
{
string filename,
	   input;

int i;
char ch;
fstream file;

//Get the file name

cout<< "Enter a file name: ";
cin >> filename;

//Open the file
file.open(filename.c_str(), ios::in);

//If the file was successfully openeed, continue
if (file)
{
	//get a character from the file
	getline(file,input);
	string tempinput=input;

	for(int i=0; i<10; i++)
	{
		cout << input;
		getline(file, input);


		if (tempinput==input)
	{
		cout <<"\n "<<endl;
		break;

		}

	}

	file.close();
	cout<<" The first 10 lines have been displayed"<<endl;
}
else
cout<<filename<< "could not be opened. \n";


cin.get();
cin.get();


return 0;

}
closed account (E0p9LyTq)
If you are using an IDE, such as Visual Studio, the file you are trying to open might need to be in a different location than where the executable file is, if you start the program from the IDE.
go to your computers library folder, then developer, then xcode, then Derived Data, then "name of your file", then build, product, debug, and put your input file in the debug folder. thats what i had to do when i had the same problem as yourself. hope this helps !
closed account (i8bjz8AR)
thanks for the responses! I'm using codeblocks and have a folder, with a file notepad with random text, all that is saved in the same folder as the program i'm running. Any other ideas?
You could try inserting some test code to write a file to the current directory and see where it appears. That is the working directory and will be where it is looking for the input file.
closed account (i8bjz8AR)
I still can't get the program to open a file, the folder name is filename, could anybody think of anything else?
Try opening a file with a unique file name for output using the ofstream class. If this file opens correctly use your file systems find functionality to locate the file. The directory where this file is located will be where you need to place your text file.

Also, if you're using Windows, make sure that you turn off the "helpful" hide known extension features and make sure the file extension of your file is correct.

Topic archived. No new replies allowed.