简体   繁体   English

使用QTextStream C ++读取txt文件

[英]Reading a txt file using QTextStream C++

I am making a small program I have done before in Java however I want to try and get the same working in C++. 我正在编写一个以前用Java完成的小程序,但是我想尝试在C ++中获得同样的效果。 The idea is to merge two text files 想法是合并两个文本文件

file1: 文件1:

a
b
c

file2: 文件2:

1
2
3

output file should read: 输出文件应为:

a1
b2
c3

I have looked at the QTextStream docs and this was the suggested code to read a file by line into strings 我看过QTextStream文档,这是建议的代码,用于将文件逐行读取为字符串

QFile file(input); // this is a name of a file text1.txt sent from main method
if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
{
    return 1;
}
QTextStream in(&file);
QString line = in.readLine();
while (!line.isNull())
{
    line = in.readLine();
}

Yet for some reason nothing is being loaded from the file at all. 但是由于某种原因,文件根本没有加载。 I proved this by printing 'line' to console and got nothing. 我通过在控制台上打印“行”来证明这一点,但一无所获。

So any ideas? 有什么想法吗? All I want is to read the file and end up with a string like this 我想要的就是读取文件并以这样的字符串结尾

QString text1 = "a\n2\n3"

I'd do this for both files, split the strings into QStringList (most likely) join them together in the format I want and write them to a 3rd txt file. 我将对两个文件都执行此操作,将字符串拆分为QStringList(最有可能)以所需的格式将它们连接在一起,然后将它们写入第3个txt文件。

Why do you read line by line if you want the entire file? 如果要整个文件,为什么要逐行阅读?

QString line = in.readAll();

ALso, your while loop is wrong, you need to while (!in.atEnd()) for the text stream instead of checking if the string is null. 同样,您的while循环是错误的,您需要对文本流使用while (!in.atEnd()) ,而不是检查字符串是否为null。

readLine won't include the new line symbol. readLine将不包含换行符号。

Anyway, it would be much easier to open both files at the same time and construct your string on the go instead of splitting and joining. 无论如何,同时打开两个文件并随时随地构造字符串而不是拆分和连接会容易得多。

QFile f1("h:/1.txt");
QFile f2("h:/2.txt");

f1.open(QIODevice::ReadOnly | QIODevice::Text);
f2.open(QIODevice::ReadOnly | QIODevice::Text);

QString s;

QTextStream s1(&f1);
QTextStream s2(&f2);

for (int i = 0; i < 3; ++i) {
    s.append(s1.readLine());
    s.append(s2.readLine());
    if (i != 2)s.append("\n");
}

如果文件名不包含完整路径,但是您非常确定文件与应用程序位于同一目录中,请使用以下应用程序路径:

QString filename = QCoreApplication::applicationDirPath() + "/" + input;

Try this block-: 试试这个块-:

while(!in.atEnd())
{
   QString line = in.readLine();   
   ....
}

do you get output using this while loop? 你使用while循环获得输出吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM