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

相关推荐
AI玫瑰助手2 小时前
Python函数:默认参数的定义与注意事项
开发语言·python·信息可视化
油炸自行车2 小时前
Claude Code 错误:API Error: 400 Failed to deserialize the JSON body into the
开发语言·javascript·json·trae·claude code·api error 400
肩上风骋2 小时前
C++14特性
开发语言·c++·c++14特性
读书札记20223 小时前
Qt界面卡死问题探讨及解决方法
qt
JAVA社区4 小时前
Java高级全套教程(十)—— SpringCloudAlibaba超详细实战详解
java·开发语言·spring cloud·面试·职场和发展
弥树子4 小时前
踩坑记录:服务器内网调用接口,真实请求URL与官方公开URL不一致问题排查
开发语言·php
z落落4 小时前
C# ToCharArray + foreach遍历 + String与StringBuilder
开发语言·c#
学代码的真由酱5 小时前
Java多用户一对一网页聊天室-测试报告
java·开发语言·功能测试·测试
人道领域5 小时前
【LeetCode刷题日记】669.修剪二叉搜索树
开发语言·python·算法
xiaoshuaishuai85 小时前
C# AvaloniaUI动态显示图片
开发语言·c#