Joshua LI
Joshua LI

Reputation: 4733

Read File Using Relative Path on Linux Qt

Original one : QFile file("/home/casper/QuickRecorder/about_content.txt"); (Work)

I have tried :

  1. "about_content.txt"
  2. "/about_content.txt"
  3. "~/about_content.txt"
  4. "./about_content.txt"
  5. "QuickRecorder/about_content.txt"
  6. "/QuickRecorder/about_content.txt"
  7. "~/QuickRecorder/about_content.txt"
  8. "~/QuickRecorder/about_content.txt"

No one works.=[


My Questions

  1. What path can I use?
  2. If I register the file "about_content.txt" into Resource, how can I read it into text browser?

The following is the entire code :

About::About(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::About)
{
    ui->setupUi(this);
    this->setFixedSize(this->width(),this->height());
    QFile file("/home/casper/QuickRecorder/about_content.txt");
    if ( !file.open(QIODevice::ReadOnly) )
        QMessageBox::information(0, "Error", file.errorString());
    QTextStream content(&file);
    ui->aboutContentBrowser->setText(content.readAll());
}

Reference : QT C++ GUI Tutorial 27- How to read text file and display file to a textbrowser or textEdit


Thank you for your help.

Upvotes: 3

Views: 7601

Answers (2)

NG_
NG_

Reputation: 7173

If you place your file about_content.txt inside build directory you can use:

  • about_content.txt
  • ./about_content.txt

If you must open file right from this path /home/casper/QuickRecorder/about_content.txt

  • Use absolute path as you wrote in question.

If you want use relative path

Take a look at differrence of relative path vs absolute path. So if you place your file for example to /home/casper/QuickRecorder/about_content.txt and you know exactly that your build lirectory is /home/casper/app-build -- you can use relative path ../QuickRecorder/about_content.txt

Take a look at QDir class. It already consists lots of useful methods.

If you want to place your file to resources

That procedure is pretty simple. Just add resource you your project and add file to your resource according to The Qt Resource System. For example, you can add your file about_content.txt to .qrc file and use it in your program this way: QFile file(":/about_content.txt");.

Upvotes: 4

TheDarkKnight
TheDarkKnight

Reputation: 27611

You can get the path of the user's home directory using the static function QDir::homePath().

QString homePath = QDir::homePath();
QFile file(homePath + "/QuickRecorder/about_content.txt");
...

Upvotes: 1

Related Questions