Question

I have this code:

int *size1 = new int();
int *size2 = new int();
QFile* file = new QFile("C:/Temp/tf.txt");
file->open(QFile::WriteOnly | QFile::Truncate);
file->write(str);
    *size1 = file->size();
file->close();
file->open(QFile::WriteOnly | QFile::Truncate);
file->write(strC);
    *size2 = file->size();
file->close();
delete file;
if (size1 < size2)
{
    return true;
}
else
{
    return false;
}
delete size1;
delete size2;

I want to compare bytes in file. But it comparing number of symbols in file.

Was it helpful?

Solution

Keep in mind that when you write a character to a file it's probably going to be a byte, for the most part anyway.

#include <QtCore/QCoreApplication>
#include <QFile>
#include <QDebug>

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);
    char *str = "Hello";

    char *strC = "Hello again!";
    qint64 size1;
    qint64 size2;
    QFile* file = new QFile("/home/nick/tf.txt");
    file->open(QFile::WriteOnly | QFile::Truncate);
    file->write(str);

    size1 = file->size();

    file->close();
    file->open(QFile::WriteOnly | QFile::Truncate);
    file->write(strC);

    size2 = file->size();

    file->close();
    delete file;

    QString num1 = QString::number(size1);
    QString num2 = QString::number(size2);
    if (size1 < size2)
    {
        qDebug() << "Returning true";
        qDebug() << "Size 1 is: " + num1;
        qDebug() << "Size 2 is: " + num2;
        return true;
    }
    else
    {
        return false;
    }

    return a.exec();
}

Modified your code slightly. This then produces:

Returning true 
"Size 1 is: 5" 
"Size 2 is: 12"

See how the file size matches the number of characters? Each character is a byte, that's why it looks like it's counted the characters.

OTHER TIPS

According to Qt's docs:

qint64 QFile::size () const [virtual]

Reimplemented from QIODevice::size().

Returns the size of the file.

For regular empty files on Unix (e.g. those in /proc), this function returns 0; the contents of such a file are generated on demand in response to you calling read().

It does return the number of bytes, not the number of characters (I'm assuming that's what you mean by "symbols". Note that size() returns a qint64, not an int.

Your code should work as expected if you use a qint64.

Also, why are you using pointers for int? There is no benefit in doing that, just create it on the stack:

qint64 size1 = 0;

qint64 size2 = 0;

Also -- comparing

if (size1 < size2)
{
    return true;
}

Is not going to do what you think, it compares ptr addresses. You probably want...

if (*size1 < *size2)
{
    return true;
}

But as Lucky Luke said, there's no reason to put these on the heap.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top