Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get filename from QFile?

Tags:

qt

qt4

People also ask

How to get file name in Qt?

QString path = f. fileName(); QString file = path. section("/",-1,-1); QString dir = path. section("/",0,-2);

How do I read a Qt file?

open(QIODevice::WriteOnly) and then write data to it. Similarly, to get data out of a file, you will need to call file. open(QIODevice::ReadOnly) and then read the data. You can do whatever you want with the data after that.

How do I open a Qt file in C++?

Try to put it in the same directory as the executable or just put the complete path into the QFile constructor. Print out the string returned by QDir::currentPath(); I bet it's different from the path where the trace. txt file is located at.

What is a QFile?

QFile is an I/O device for reading and writing text and binary files and resources. A QFile may be used by itself or, more conveniently, with a QTextStream or QDataStream. The file name is usually passed in the constructor, but it can be set at any time using setFileName().


Use a QFileInfo to strip out the path (if any):

QFileInfo fileInfo(f.fileName());
QString filename(fileInfo.fileName());

One approach, not necessarily the best: from a QFile, you can get the file specification with QFile::fileName():

QFile f("/home/umanga/Desktop/image.jpg");
QString str = f.fileName();

then you can just use the string features like QString::split:

QStringList parts = str.split("/");
QString lastBit = parts.at(parts.size()-1);

just in addition: to seperate filename and file path having QFile f

QString path = f.fileName();
QString file = path.section("/",-1,-1);
QString dir = path.section("/",0,-2);

you don't need to create an additional fileInfo.


I use this:

bool utes::pathsplit(QString source,QString *path,QString *filename)
{
QString fn;
int index;
    if (source == "") return(false);
    fn = source.section("/", -1, -1);
    if (fn == "") return(false);
    index = source.indexOf(fn);
    if (index == -1) return(false);
    *path = source.mid(0,index);
    *filename = fn;
    return(true);
}