QT4 and databases

I've read and copied/pasted the examples on this web site: http://www.cplusplus.com/doc/tutorial/files/

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.

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
// writing on a text file
#include <iostream>
#include <fstream>
using namespace 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>
using namespace 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.

-Albatross
Topic archived. No new replies allowed.