qt-文件系统

路径是否存在

QString tmpPath = "D:\\zhengjun\\remoteCom\\Win32\\Debug";
QDir dir(tmpPath);
if (dir.exists())
{
QString fileTest = tmpPath + "\\QTTest.cfg";
if(QFile::exists(fileTest))
QFile::remove(fileTest);

QFile f(fileTest);
f.open(QIODevice::ReadWrite | QIODevice::Text);
QTextStream ft(&f);
ft<<param;
f.close();
}

获取应用路径

QString strPath = QCoreApplication::applicationDirPath();
strPath += "/comBySocket.exe";

设置应用路径

QString appPath = argv[0];
QDir appDir(appPath);
QString appName = appDir.dirName();
g_appPath = appPath.left(appPath.length()-appName.length());

if (false == QDir::setCurrent(g_appPath))
{
qDebug("set working path failed.");
}else{
QString strLog = "set working path success:" + g_appPath;
qDebug(strLog.toLatin1().data());
}

写二进制文件

QFile file("d:\\audio.pcm");  
file.open(QIODevice :: WriteOnly | QIODevice :: Append);
QDataStream out(&file);
//--向文件写入数据
out.writeRawData((const char*)(pData+16),dwSize);
file.close();

读二进制文件


写文本文件

#include <QtCore/QTextStream>
#include <QtCore/QFile>
#include <QtCore/QIODevice>

QString sFilePath = "C:\\test.txt";

QFile file(sFilePath);
//方式:Append为追加,WriteOnly,ReadOnly
if (!file.open(QIODevice::WriteOnly|QIODevice::Text)) {
QMessageBox::critical(NULL, "提示", "无法创建文件");
return -1;
}
QTextStream out(&file);
out<<"要写入内容"<<endl;
out.flush();
file.close();