简体   繁体   中英

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++. The idea is to merge two text files

file1:

a
b
c

file2:

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

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.

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.

readLine won't include the new line symbol.

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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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