在Qt中,你可以使用QTextStream的<<
操作符将文本逐行写入文件。以下是一个示例代码:
#include <QCoreApplication>
#include <QFile>
#include <QTextStream>
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
QString filePath = "/path/to/file.txt"; // 文件路径
QFile file(filePath);
if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) {
qDebug() << "Failed to open file for writing: " << filePath;
return 1;
}
QTextStream out(&file);
out << "Line 1" << endl;
out << "Line 2" << endl;
out << "Line 3" << endl;
file.close();
return a.exec();
}
在上述示例中,我们使用了<<
操作符将每行文本写入文件。通过在每行结束时添加endl
来表示换行。
请注意,在运行此代码之前,请确保你有适当的权限来写入目标文件。
内容由零声教学AI助手提供,问题来源于学员提问