PDA

View Full Version : Input a text file



dwarnold45
30th March 2010, 00:34
Hi,

I am using Qt Creator on a Macbook Pro runing 10.6.2.

I've been successful with the following code and resource file:

#include <QTextStream>
#include <QFile>

int main()
{
QFile data(":/input.txt");

QString line;

if (data.open(QFile::ReadOnly)) {
QTextStream in(&data);
QTextStream out(stdout);

out.setCodec("UTF-8");
in.setCodec("UTF-8");

do {
line = in.readLine();
out << line << endl;
} while (!line.isNull());
} else {
QTextStream out(stdout);
out << "File not found" << endl;
}

}

Resource file:

<RCC>
<qresource prefix="/">
<file>input.txt</file>
</qresource>
</RCC>

Project file:

SOURCES += file.cpp
RESOURCES += file.qrc

I was trying to do this without a resource file with input.txt in the same directory as all the other project files, but no luck. Here was my attempt, which did not work:

#include <QTextStream>
#include <QFile>

int main()
{
QFile data("input.txt");

QString line;

if (data.open(QFile::ReadOnly)) {
QTextStream in(&data);
QTextStream out(stdout);

out.setCodec("UTF-8");
in.setCodec("UTF-8");

do {
line = in.readLine();
out << line << endl;
} while (!line.isNull());
} else {
QTextStream out(stdout);
out << "File not found" << endl;
}

}

You'll note the only change was to this line:

QFile data("input.txt");

I am wondering why this did not work.

David

tsp
30th March 2010, 06:09
At least in Windows the executable is (by default) either in debug/release folder and you need to put your text file into debug/release folder instead of the folder where project files are.

Lykurg
30th March 2010, 06:47
It is not working because your path is wrong. Obviously. It's a relativ path and the starting point is the folder in your application executable. So use an absolute path or a right relative one. Since the wiki is down and and I don't have a mac, I think it was something like that:
QDir dir(QCoreApplication::applicationDirPath());
dir.up();
dir.up();And then you should be in the "root" directory of your project.