Reputation: 4479
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?
Upvotes: 1
Views: 1889
Reputation: 1674
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.
Upvotes: 0
Reputation: 977
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.
Upvotes: 0
Reputation: 27611
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
Upvotes: 1