Qt creator - problem with <fstream>

I'm using qt creator on MacOS and I have a problem with compiling my programs. Everytime I try to open txt file with:

fstream file;
file.open("test.txt");
if (file.good())

I get this in the console:

source /var/folders/qx/cpz2lwwx1pd9l1njfddzdxc80000gn/T/tmp6tPViX
Any ideas how to solve it ?
Step 1: improve the syntax:
1
2
3
std::fstream file("test.txt");
if ( file ) {
    ...


Step 2: check your file position.
Assuming your project name is “catsanddogs”, on your hd there should be a directory named “catsanddogs” which should contain a “catsanddogs.pro” file
and
another directory named “build-catsanddogs…”
where you should find both a “debug” and a “release” directories.

“test.txt”should be placed inside this directory.
What is inside your actual if statement? There must be something.

If test.txt is an existing file, do ifstream instead of fstream.

And, do:
1
2
3
4
5
6
7
8
if (file)
{
    cout << "FILE OPENED\n";
}
else
{
    cout << "FILE NOT OPENED\n";
}

If it's not opening the file, then do the aforementioned troubleshooting steps.

On mac/linux/unix you can do system("pwd"); to have it print the current working directory. On Windows, you can do system("cd"); to have it print the current working directory.
Put the test.txt in that folder.
Last edited on
Ganado wrote:
on Windows, you can do system("cd"); to have it print the current working directory

Wasn’t it system("dir"); ?
dir is the Windows sort-of equivalent to ls (shows you files/directories within the current directory)
Last edited on
I have no trouble with QtCreator - lucky me.

However, even though I haven't read it in great detail, this link might be of use
https://github.com/ocaml/opam/issues/3576
A bit further investigation confirms it's all to do with paths etc:

A simple 'fix' is to put the text file in some directory (here I put it in "/Users/againtry/" ) and call it up explicitly in the program as follows.

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
#include <iostream>
#include <fstream>
#include <string>

using namespace std;

int main()
{
    fstream file;
    file.open("/Users/againtry/test.txt");
    string line;

    cout << true << ' ' << file.good() << '\n';

    if (file.good() == true)
    {
        getline(file, line);

        cout << line << '\n';
        cout << "File is good\n";
    }
    else
        cout << "File is not good\n";

    cout << "Hello World!" << endl;
    return 0;
}



/Users/againtry/qtstuff_and_nonsense/build-untitled-Desktop_Qt_5_14_0_clang_64bit-Debug/untitled ; exit;
1 1
First line of text
File is good
Hello World!
If you use Qt Creator, do you use Qt as well?

Qt has QFile, QFileInfo, QDir, etc. Portable abstractions.
See: https://doc.qt.io/qt-5/qfile.html#setFileName

QFile and QFile::setFileName is essentially the same problem of clearly and explicitly defining, somehow or other, the path to the relevant file.
Last edited on
Topic archived. No new replies allowed.