C++ 如何使用readline()在qt中使用相同的换行符获得与原始文件相同的文件?
我想写一个qt函数来复制一个文件。但是,我无法复制真正相同的文件,因为“\n”不能保留相同的文件 例如,我的测试代码C++ 如何使用readline()在qt中使用相同的换行符获得与原始文件相同的文件?,c++,qt,C++,Qt,我想写一个qt函数来复制一个文件。但是,我无法复制真正相同的文件,因为“\n”不能保留相同的文件 例如,我的测试代码 void testFile() { QFile inFile(":/testFile-ANSI-win.txt"); if (!inFile.open(QIODevice::ReadOnly | QIODevice::Text)) return; QFile outFile("../testFile-ANSI-win-readline-b
void testFile()
{
QFile inFile(":/testFile-ANSI-win.txt");
if (!inFile.open(QIODevice::ReadOnly | QIODevice::Text))
return;
QFile outFile("../testFile-ANSI-win-readline-bak.txt");
if (!outFile.open(QIODevice::WriteOnly | QIODevice::Truncate))
return;
QTextStream in(&inFile);
QTextStream out(&outFile);
out.setCodec("UTF-8");
while (!in.atEnd())
{
QString line = in.readLine();
out << line;
out << "\r\n";
}
}
但我的输出文件是:
11111
22222
33333
11111
22222
33333
// Fail to be the same. There is a new line, but I don't want it
11111
22222
// ends with the empty line
11111
22222
// Same!!
当输入文件以空行结束时,该函数运行良好。输出文件与输入文件相同。我的输入文件是:
11111
22222
33333
11111
22222
33333
// Fail to be the same. There is a new line, but I don't want it
11111
22222
// ends with the empty line
11111
22222
// Same!!
但我的输出文件是:
11111
22222
33333
11111
22222
33333
// Fail to be the same. There is a new line, but I don't want it
11111
22222
// ends with the empty line
11111
22222
// Same!!
是否可以使用readLine()函数从源文件复制相同的文件
类似问题:
您可以读取字符串中的所有输入,将字符串拆分为行,输出行,在每行之前插入新行,在第一行之后插入新行 比如:
QString all = inFile.readAll();
QStringList lines = all.split('\n');
QTextStream out(&outFile);
out.setCodec("UTF-8");
QString line;
for(int i=0; i<lines.size(); i++)
{
if(i>0)
{
out << endl;
}
line = lines.at(i);
out << line;
}
QString all=infle.readAll();
QStringList行=all.split('\n');
QTextStream out(&outFile);
out.setCodec(“UTF-8”);
QString线;
对于(int i=0;i0)
{
从文档中删除:返回的行没有行尾字符(“\n”或“\r\n”)
因此,您无法知道原始文件是否有换行符。如果确实需要,您可以通过在文件结尾之前搜索seek
来作弊并查看infle
的最后几个字节。使用静态函数QFile::copy
它将在Windows上以1:1的比例复制文件。QF文件::复制(“C:\input.txt”,“C:\\out.txt”)
@user3606329不,QFile::copy
不能复制同一个文件。我有测试。你可以用我的第一个测试输入进行测试。你会发现输出在文件末尾还有一个换行。@Botje我已经阅读了官方文档。peek
技巧不是我想要的。谢谢你。@JosanSun你知道吗me编辑器(例如Geany)在缺少一行的文本文件末尾显示换行符?是的。这太棒了!