text file directory

hi,

how do I put a text file in the same directory with my cpp codings so I can open the file and take something out of it?
By default, whatever text file you create in the program, it will store in the same directory of your Project
I created the text file in visual studio where I write the codes but still it says thatitcould not open the file is something wrong with the code?
void main()
{
string line;
ifstream myfile ("TextFile1.txt");
//vector<int>myvector;
if(myfile.is_open())
{
while(!myfile.eof())
{
getline(myfile,line);
//myvector.push_back(line);
cout<<line<<endl;
}

myfile.close();
}
else
{
cout<<"file did not open"<<endl;
}


system("pause");

}
Your code looks fine. Try replacing the if(myfile.is_open()) with If(myfile)
And also whether did u put your textfile in the same directory as project
An ofstream will create a file in the same directory that an ifstream would be looking for one. You could make a quick program:
1
2
3
4
5
6
7
int main()
{
  ofstream where("here.txt");
  where << "Hello";
  where.close();
  return 0;
}


Figure out where the file is and that is where you should put TextFile1
I created the text file in visual studio where I write the codes but still it says thatitcould not open the file is something wrong with the code?

There's nothing obviously wrong with the code.

The problem is, the text file needs to be in the same path as the executable program. When your program is compiled and linked, the actual program which is run by the computer may be in some sub-directory, such as "Release" or "Debug" or whatever is the default for your system.

Alternatively, instead of just the file-name, you could supply the complete filename including the full path, e.g. "D:\\data\\TextFile1.txt". Note that '\' is used to indicate special characters such as '\n' for newline, so it needs to be entered as "\\".
Last edited on
add this
system("dir TextFile1.*");

after
cout<<"file did not open"<<endl;

make sure your file name is not TextFile1.txt.txt

thank you guys! I finally figured it out and it got me thinking that if it took me that long how am I gonna figure the rest of the huge c++ language but still its good to try
Topic archived. No new replies allowed.