简体   繁体   中英

Qt, read in a local text file

I have tried to use QFile to open a text file: I tried

QFile file("serial_deviceIP.txt");

but the file.open() returns false.

However, if I switched to a global address like:

QFile file("C:/Users/shupeng/Documents/qgroundcontrol_peidong_mod/serial_deviceIP.txt");

it works. Why? How can I solve this?

In the first instance, the path to the file cannot be found.

QFile file("serial_deviceIP.txt");

This specifies the file with a relative path, and will only work if serial_deviceIP.txt is in the current working directory , which is likely to be the directory that contains the executable of your program.

QFile file("C:/Users/shupeng/Documents/qgroundcontrol_peidong_mod/serial_deviceIP.txt");

This is referencing an absolute file path, so the file will be found

You can also use Qt's Resource System to bundle the files with your application.

Create a .qrc file in your project and add any file you wish to use/load in your application to it.

Then you can load your file as:

QFile file( ":myfiles/serial_deviceIP.txt" );

See QT Resource System for more information.

What happens is that when we are developing our code we usually keep our project source dir on mind as the reference so we don't give an absolute path, but after building the current directory will change and it will be the build directory, so our application won't find the files without a absolute path.

A possible solution is to add a Resources in our project including our project directory. So just add the following line in the project_file.pro :

RESOURCES += ./

and then use the character : before the file's name when you go to read it, like it:

QFile foo(":bar.txt")

That just work for read it but not for write. So to write is necessary specify an absolute path.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM