The article show demoes about use ifstream to read file written by qfile and use qfile to read file written by ofstream.

Use ifstream to read file written by QFile

#include <QCoreApplication>
#include <QString>
#include <QFile>
#include <iostream>
#include <fstream>

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);
    QString path = "test.txt";
    QFile writeFile(path);
    writeFile.open(QIODevice::WriteOnly);
    if (writeFile.isOpen())
    {
        int version = 6;
        writeFile.write((char*)&version, sizeof(int));

        char str[10] = "hello~";
        writeFile.write(str, sizeof(str));

        writeFile.close();
    }

    std::ifstream iStream;
    iStream.open(path.toLocal8Bit().data(), std::ios::binary);
    if( iStream.is_open() )
    {
        int version = -1;
        iStream.read((char*)&version, sizeof(version));

        char str[10] = { 0 };
        iStream.read(str, sizeof(str));

        std::cout << version << " " << str << std::endl;

        iStream.close();
    }
    return a.exec();
}

Output:

6 hello~

Use QFile to read file written by ofstream

#include <QCoreApplication>
#include <QString>
#include <QStringList>
#include <QDebug>
#include <QFile>
#include <iostream>
#include <fstream>

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);
    QString path = "test.txt";

    std::ofstream oStream;
    oStream.open(path.toLocal8Bit().data(), std::ios::binary);
    if( oStream.is_open() )
    {
        int version = 6;
        oStream.write((char*)&version, sizeof(version));

        char str[10] = "hello~";
        oStream.write(str, sizeof(str));

        oStream.close();
    }

    QFile readFile(path);
    readFile.open(QIODevice::ReadOnly);
    if (readFile.isOpen())
    {
        int version = -1;
        readFile.read((char*)&version, sizeof(int));

        char str[10] = { 0 };
        readFile.read(str, sizeof(str));

        std::cout << version << " " << str << std::endl;

        readFile.close();
    }

    return a.exec();
}
Categories: CPlusPlus

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments

Tex To PDF
: convert the Latex file which suffix is tex to a PDF file

X
0
Would love your thoughts, please comment.x
()
x