c++ - QFile not reading file -


i trying read simple text file using qfile (qt5), strangely doesn't work. below code.

qfile*file = new qfile("gh.txt"); if(file->open(qiodevice::readonly)) {     qbytearray array;     array = file->readline();     qdebug() << array; } file->close(); 

qdebug gets empty string.#

qfile *file = new qfile("gh.txt"); //                      ^^^^^^^^ 

the issue trying open file in current working directory.

you should use code fix it:

qfile file(qcoreapplication::applicationdirpath() + "gh.txt"); 

also, not see point in allocating qfile instance on heap. should use stack object here per above line.

actually, code leak memory explicit deletion pointless if use stack objects.

moreover, there no need call close explicitly. c++, , have got raii. called automatically destructor of qfile class.

also, despite writing open succeeded, did not. should prepare proper error reporting when not successful using file.errorstring() method.

so, taking account, code this:

qfile file(qcoreapplication::applicationdirpath() + "gh.txt"); if (!file.open(qiodevice::readonly))     qdebug() << "failed open file:" << file.filename() << "error:" << file.errorstring(); else     qdebug() << file->readline(); 

it possible file not next executable in case move there.

qfile support relative paths, not idea use because can relative different installation potentially break application others.


Comments

Popular posts from this blog

commonjs - How to write a typescript definition file for a node module that exports a function? -

openid - Okta: Failed to get authorization code through API call -

thorough guide for profiling racket code -