qt 可以在一个函数中读一个文件,然后再将内容写入另一个文件中

是的,Qt 允许你在一个函数中读取一个文件的内容,并将这些内容写入到另一个文件中。这可以通过结合使用 QFileQTextStream(或 QDataStream,取决于你的具体需求)来实现。以下是一个简单的示例,展示了如何在一个函数中完成这个任务:

复制代码
#include <QFile>  
#include <QTextStream>  
#include <QDebug>  
  
bool copyFileContent(const QString &sourceFile, const QString &destinationFile) {  
    QFile sourceFileHandle(sourceFile);  
    QFile destinationFileHandle(destinationFile);  
  
    if (!sourceFileHandle.open(QIODevice::ReadOnly | QIODevice::Text)) {  
        qDebug() << "无法打开源文件:" << sourceFile;  
        return false;  
    }  
  
    if (!destinationFileHandle.open(QIODevice::WriteOnly | QIODevice::Text)) {  
        qDebug() << "无法打开目标文件:" << destinationFile;  
        return false;  
    }  
  
    QTextStream sourceStream(&sourceFileHandle);  
    QTextStream destinationStream(&destinationFileHandle);  
  
    while (!sourceStream.atEnd()) {  
        QString line = sourceStream.readLine();  
        destinationStream << line << endl; // 写入目标文件,并添加换行符  
    }  
  
    sourceFileHandle.close();  
    destinationFileHandle.close();  
  
    return true;  
}  
  
int main() {  
    QString sourceFile = "path/to/source.txt";  
    QString destinationFile = "path/to/destination.txt";  
  
    if (copyFileContent(sourceFile, destinationFile)) {  
        qDebug() << "文件内容复制成功!";  
    } else {  
        qDebug() << "文件内容复制失败!";  
    }  
  
    return 0;  
}

在这个示例中,copyFileContent 函数接受两个参数:源文件的路径和目标文件的路径。它首先尝试打开这两个文件,然后使用 QTextStream 来读取源文件的内容,并将这些内容逐行写入目标文件。如果文件操作成功,函数返回 true;否则,返回 false

请注意,你需要根据实际情况替换 sourceFiledestinationFile 变量的值,以指向正确的文件路径。此外,这个示例假设文件是以文本模式打开的;如果你需要处理二进制文件,你应该去掉 QIODevice::Text 标志,并可能需要使用 QDataStream 而不是 QTextStream

相关推荐
侃侃_天下2 天前
最终的信号类
开发语言·c++·算法
echoarts2 天前
Rayon Rust中的数据并行库入门教程
开发语言·其他·算法·rust
Aomnitrix2 天前
知识管理新范式——cpolar+Wiki.js打造企业级分布式知识库
开发语言·javascript·分布式
每天回答3个问题2 天前
UE5C++编译遇到MSB3073
开发语言·c++·ue5
伍哥的传说2 天前
Vite Plugin PWA – 零配置构建现代渐进式Web应用
开发语言·前端·javascript·web app·pwa·service worker·workbox
小莞尔2 天前
【51单片机】【protues仿真】 基于51单片机八路抢答器系统
c语言·开发语言·单片机·嵌入式硬件·51单片机
我是菜鸟0713号2 天前
Qt 中 OPC UA 通讯实战
开发语言·qt
JCBP_2 天前
QT(4)
开发语言·汇编·c++·qt·算法
Brookty2 天前
【JavaEE】线程安全-内存可见性、指令全排序
java·开发语言·后端·java-ee·线程安全·内存可见性·指令重排序
百锦再2 天前
[特殊字符] Python在CentOS系统执行深度指南
开发语言·python·plotly·django·centos·virtualenv·pygame