While the program creates the example.txt just fine, I cannot do anything with it after that as the file is no longer found by the subsequent program that reads this newly created file. I'm struggling like crazy with with file creation/manipulation. Can someone please help me get this straightened out? Below is the code that writes (creates) the file, and the next is where it tries to read it but can't find the file. I'm using Linux Mint with QT4.
// writing on a text file
#include <iostream>
#include <fstream>
usingnamespace std;
int main () {
ofstream myfile ("example.txt");
if (myfile.is_open())
{
myfile << "This is a line.\n";
myfile << "This is another line.\n";
myfile.close();
}
else cout << "Unable to open file";
return 0;
}
[/code
]
*********************************************
*********************************************
[code]
// reading a text file
#include <iostream>
#include <fstream>
#include <string>
usingnamespace std;
int main () {
string line;
ifstream myfile ("example.txt");
if (myfile.is_open())
{
while ( myfile.good() )
{
getline (myfile,line);
cout << line << endl;
}
myfile.close();
}
else cout << "Unable to open file";
return 0;
}
When I run the second program, it can't find the file (although a file search proves it exists) and goes all the way down to the last line of code and executes it:
else cout << "Unable to open file";
So what is wrong here? I'm copying and pasting for crying out loud! =)
If you're running your programs from different working directories, then that could explain something about why your second program is having trouble finding your file: because it's looking in the wrong place. :)
Does the problem go away if you change the paths to your files in your programs to something that will never change depending on where your programs are placed/run from?
Also, you might want to check line 17 of what you posted here.