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

相关推荐
一只小小汤圆11 分钟前
如何xml序列化 和反序列化类中包含的类
xml·开发语言·c#
南枝异客17 分钟前
电话号码的字母组合
开发语言·javascript·算法
未来并未来42 分钟前
Sentinel 流量控制安装与使用
开发语言·python·sentinel
Halo_tjn1 小时前
Java IO
java·开发语言
我命由我123451 小时前
STM32 开发 - 中断案例(中断概述、STM32 的中断、NVIC 嵌套向量中断控制器、外部中断配置寄存器组、EXTI 外部中断控制器、实例实操)
c语言·开发语言·c++·stm32·单片机·嵌入式硬件·嵌入式
东皇太星1 小时前
Python 100个常用函数全面解析
开发语言·python
宋一平工作室2 小时前
单片机队列功能模块的实战和应用
c语言·开发语言·stm32·单片机·嵌入式硬件
笨笨马甲2 小时前
Qt Http Server模块功能及架构
qt·http·架构
豆豆(设计前端)2 小时前
在 JavaScript 中,你可以使用 Date 对象来获取 当前日期 和 当前时间、当前年份。
开发语言·javascript·ecmascript
freyazzr3 小时前
TCP/IP 网络编程 | Reactor事件处理模式
开发语言·网络·c++·网络协议·tcp/ip