【QT Creator学习记录】QDir, QFile, CSV文件 简单使用与代码示例

目录

一、QDir

1. 创建文件夹 mkdir()  mkpath()

2. 删除文件夹  rmdir() rmpath()

3. 重命名文件夹 rename()

二、QFlie

1. 创建文件 open(QIODevice::方式)

2. 判断文件是否存在 exists()

3. 删除文件 remove()

4. 重命名文件 rename(”newname“)

5. 复制文件 QFile::copy(”原地址,要复制的位置”)

6. 获取文件信息 QFileInfo

7. 写入文件 wirte() 、QTextStream()

8. 读取文件 QByteArray、 QTextStream

一、QDir

官方文档:

  • A QDir is used to manipulate path names, access information regarding paths and files, and manipulate the underlying file system. It can also be used to access Qt's resource system.
  • Qt uses "/" as a universal directory separator in the same way that "/" is used as a path separator in URLs. If you always use "/" as a directory separator, Qt will translate your paths to conform to the underlying operating system.
  • A QDir can point to a file using either a relative or an absolute path. Absolute paths begin with the directory separator (optionally preceded by a drive specification under Windows). Relative file names begin with a directory name or a file name and specify a path relative to the current directory.
  • QDir被用于操作路径名、访问相关的路径文件信息操作底层文件系统,也常被用于访问Qt资源系统
  • Qt使用”/“作为通用目录分隔符,就如同URLs中的路径分隔符一般。Qt会将带有”/“的路径转译,以便符合底层操作系统。
  • QDir可以指向相对或绝对路径。绝对路径以目录分隔符作为起始(可选:windows驱动器规范前);相对路径以目录名或文件名作为起始。
  • Examples of absolute paths:
//绝对路径absolute path
QDir("/home/user/Documents")
QDir("C:/Users")

//相对路径relative path
QDir("images/landscape.png")

1. 创建文件夹 mkdir()  mkpath()

  • mkdir()方法:如果目录不存在,则创建一个新目录。

代码示例

    //创建对象
    QDir dir_1;
    //.标识当前当前文件夹
    //相对路径下创建名为csvFile的文件夹
    dir_1.mkdir("./csvFile");

    //exists()方法检测文件目录是否存在 
    //检测是否有名为csvFile的文件,存在返回true,否则false。
    if(dir_1.exists("./csvFile")){
        qDebug()<<"文件目录已存在"<<endl;
    }

 运行结果:debug文件夹下生成对应文件

  •  mkpath()方法:如果csvFile目录的上级目录test不存在,直接创建test后创建csvFile,用于创建多级目录

代码示例

    QDir dir_2;
    dir_2.mkpath("./test/csvFile");

    if(dir_2.exists("./test/csvFile")){
        qDebug()<<"文件目录已存在"<<endl;
    }

 运行结果:

 

2. 删除文件夹  rmdir() rmpath()

  •  rmdir方法:删除指定文件夹,若文件夹不为空,删除失败
    QDir dir_3;
    dir_3.rmdir("./csvFile");
  • rmpath方法:删除指定多级文件夹,若文件夹不为空,删除失败
    QDir dir_3;
    dir_3.rmpath("./test/csvFile");
  • removeRecursively方法无论文件夹中是否存在文件,全部删除
    dir.removeRecursively("./test/csvFile");

3. 重命名文件夹 rename()

  • rename方法:旧文件夹名,新文件文件夹名。(带路径)
    QDir dirOld(oldPath);
	dirOld.rename(oldPath, newPath);

二、QFlie

官方文档:

  • 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(). QFile expects the file separator to be '/' regardless of operating system. The use of other separators (e.g., '\') is not supported.
  • You can check for a file's existence using exists(), and remove a file using remove(). (More advanced file system related operations are provided by QFileInfo and QDir.)
  • The file is opened with open(), closed with close(), and flushed with flush(). Data is usually read and written using QDataStream or QTextStream, but you can also call the QIODevice-inherited functions read(), readLine(), readAll(), write(). QFile also inherits getChar(), putChar(), and ungetChar(), which work one character at a time.
  • The size of the file is returned by size(). You can get the current file position using pos(), or move to a new file position using seek(). If you've reached the end of the file, atEnd()
  • QFile是用于读取与修改文本、二进制文件、资源的I/O设备。
  • 文件名通常在构造函数中pass,但它可以在任何时候通过setFlieName方法修改,文件路径用’/’分隔符分开,不支持其他符号。
  • 可以用exists方法检测文件是否存在,用remove方法删除文件。
  • 打开文件用open(), 关闭使用close(), 情况缓冲区数据用flush(),数据常常使用QDataStream或者QTextStream来读取修改,但你也可用QIODevice继承的方法,例如:read(), readLine(), readAll(), write()等等。
  • 使用size方法查看文件大小,获取当前文件位置使用pos方法。移动到新文件位置使用seek(),想跳转文件末尾用atEnd()

1. 创建文件 open(QIODevice::方式)

  •  open方法的打开方式:
QIODevice::ReadOnly以只读方式打开文件
QIODevice::WriteOnly只写方式
QIODevice::ReadWrite读写方式
QIODevice::Append追加模式打开,新写入文件的数据添加到文件尾部
QIODevice::Truncate截取方式打开文件,文件原有的内容全部被删除
QIODevice::Text文本方式打开文件,读取时“\n”被自动翻译为换行符
  • open里的打开模式为QIODevice::WriteOnlyQIODevice::ReadWriteQIODevice::Append这三种的话,文件不存在则会自动创建出一个空文件出来
  • 这些取值可以用“|”组合使用,例如 QIODevice::ReadOnly | QIODevice::Text 表示以只读和文本方式打开文件。

代码示例

    QFile f("./test/xxx.csv");
    if(!f.open(QIODevice::Append))
    {
       qDebug()<<"创建成功啦"<<endl;
    }else{
       qDebug()<<"创建失败啦"<<endl;
    }

2. 判断文件是否存在 exists()

  • exists方法:存在返回true,否则false。
    QFile f("./test/xxx.csv");
    if(f.exists())
    {
       qDebug()<<"文件存在"<<endl;
    }else{
       qDebug()<<"文件不存在"<<endl;
    }

3. 删除文件 remove()

  • remove方法:成功true,失败false
    QFile f("./test/xxx.csv");
    if(f.remove())
    {
       qDebug()<<"删除成功"<<endl;
    }else{
       qDebug()<<"删除失败"<<endl;
    }

4. 重命名文件 rename(”newname“)

    QFile f("./test/xxx.csv");
    f.rename("新名称");

5. 复制文件 QFile::copy(”原地址,要复制的位置”)

    QFile::copy("./test/xxx.csv","./test/xxx2.csv");

6. 获取文件信息 QFileInfo

  • QFileInfo类创建对象info,将对象f 作为参数。

 代码示例

    QFile f("./test/xxx.csv");
    QFileInfo info(f);
    qDebug()<<"文件名"<<info.fileName()<<endl;
    qDebug()<<"基本名称"<<info.baseName()<<endl;
    qDebug()<<"后缀"<<info.suffix()<<endl;
    qDebug()<<"创建时间"<<info.birthTime()<<endl;
    qDebug()<<"大小"<<info.size()<<endl;

运行结果:

/*

件名 "xxx.csv"

基本名称 "xxx"

后缀 "csv"

创建时间 QDateTime(2023-09-27 15:45:01.484 中国标准时间 Qt::LocalTime)

大小 3

*/

7. 写入文件 wirte() 、QTextStream()

什么是CSV文件?

  • CSV文件以纯文本格式存储的表格数据(数字和文本)。CSV文件由任意数目的记录组成,记录间以某种换行符分隔;每条记录由字段组成,字段间的分隔符是其它字符或字符串,最常见的是逗号制表符。通常,所有记录都有完全相同的字段序列。
  • CSV全称Comma-Separated Values,即逗号分隔值,有时也称为字符分隔值,因为分隔字符也可以不是逗号。最常见的分隔符是逗号或制表符。CSV文件可以被认为是一个“平面文件数据库”。
  • CSV数据交换格式是一种通用的、相对简单的文件格式,被用户、商业和科学广泛应用,最常用于程序之间传输表格数据。大部分程序都支持某种CSV变体,至少是作为一种可选择的输入或输出格式。
  • CSV没有通用标准规范,不同的程序间CSV的标准有差异很常见,因此,术语“CSV”泛指具有以下特征的任何文件:
    • 纯文本,使用某个字符集,比如ASCII、Unicode、UTF-8或GB2312;
    • 由记录组成(典型的是每行一条记录);
    • 每条记录被分隔符分隔为字段
    • 每条记录都有同样的字段序列
  • CSV文件格式非常简单,被几乎所有的电子表格(如Excel、WPS、Numbers 表格)和数据库管理系统支持。许多编程语言都有可利用的库来支持CSV文件。
  • 写入方式2种,分别使用wirte() ,QTextStream()

代码示例

    //创建对象
    QFile f("./test/xxx.csv");
    //打开文件:以读写方式
    f.open(QIODevice::ReadWrite	);

    //方式1
    QByteArray qba = "A,B,C,D,E,F,G\rG,F,E,D,C,B,A";
    f.write(qba);

    //方式2
    QTextStream qts(&f);
    QString str1="1,2,3,4,5,6,7";
    QString str2="1,2,3,4,5,6,7";
    QString str3="A,B,C,D,E,F,G";
    //endl为换行
    qts<< str1 <<endl << str2 <<str3;

    //关闭文件,否则文件会被锁定导致其他软件无法打开
    f.close();
  • 其中qba中”,“是字符分隔值\r为换行

运行结果如下:

/*

wirte() 方式写入:

QTextStream()方式写入:

*/

  • 可以看到str2与str3不换行, 会直接将7与A视为同一字段

8. 读取文件 QByteArray、 QTextStream

代码示例

    //方式1
    QByteArray array2 = f.readAll();
    qDebug() << array2;

    //方式2
    QTextStream in(&f);
    while (!f.atEnd()) {
       QString line = f.readLine();
       qDebug() << line;
    }

运行结果:

/*

方式1:

"1,2,3,4,5,6,7\n1,2,3,4,5,6,7\nA,B,C,D,E,F,G”

方式2:

"1,2,3,4,5,6,7\n" "1,2,3,4,5,6,7\n" "A,B,C,D,E,F,G"

*/

  • 方式1:可以看到readAll()直接都打印出来了,包括分隔符换行符,如果需要显示格式,需要循环遍历分隔符和换行符,也是使用readLine方法。
  • 方式2:QTextStreamatEnd()方法去做while循环可以一行行读数据,方便很多。
  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值