1

我正在使用 Qt creator 做一个项目。我有 3 个屏幕,每个屏幕有 4 个按钮。当单击第一个按钮时,它会将 0 写入文件(字符),依此类推到 3。当我到达最后一个屏幕(4.屏幕)时,我将从文件中读取并显示按钮的输入3个字符。

void fileOperation::openFileWrite(char x, off_t s)
{
    int fd;
    char c[2] = {x};

    fd = open("/home/stud/txtFile", O_CREAT | O_WRONLY, 0666);//open file
    if(fd == -1)
        cout << "can't open file" << endl;
    else
    {
        lseek(fd, s, SEEK_SET);//seek at first byte
        write(fd, (void*)&c, 2);//write to file
    }
    //syncfs(fd);
    ::close(fd);
}

QString fileOperation::openFileRead()
{
    int fd;
    QString str;
    char c[4];

    fd = open("/home/stud/txtFile", O_RDWR);
    lseek(fd, 0, SEEK_SET);
    read(fd, (void*) &c, 4);
    str = QString(c);
    return str;
    ::close(fd);
}

当我关闭应用程序并使用按钮的新输入再次打开它时,它会在最后一个屏幕中显示上一个输入。任何解决此问题的建议或帮助。

4

1 回答 1

1

您的代码存在多个问题:

  • 函数名很奇怪

  • 在 write 系统调用之后,您没有检查错误。

  • 您没有在 lseek 系统调用之后检查错误。

  • 您没有在关闭系统调用后检查错误。

  • 您不一致地使用::前缀来关闭系统调用,而不是其余的。

  • 即使打开不成功,您也试图关闭。

  • 您正在尝试将 2 个字符写入文件,但随后您正在尝试回读 4 个字符。

  • 您在评论后面有一个剩余的syncfs。

  • 您对主路径进行了硬编码,而不是使用一些主变量。

  • 您试图在读取中创建一个多余的临时变量“str”。

  • 您正试图在返回那里后关闭。

  • 您的代码是非常特定于平台的,而您已经依赖于 Qt。

我会亲自扔掉你的代码并改用这个:

主文件

#include <QString>
#include <QFile>
#include <QDir>
#include <QDebug>

class fileOperation
{
    public:
    static void write(char x, off_t s = 0)
    {
        QFile file(QDir::homePath() + "/file.txt");
        if (!file.open(QIODevice::WriteOnly | QIODevice::Unbuffered)) {
            qDebug() << file.errorString();
            return;
        }

        if (s && !file.seek(s)) {
            qDebug() << file.errorString();
            return;
        }

        if (file.write(&x, 1) != 1) {
            qDebug() << file.errorString();
            return;
        }
    }

    static QString read()
    {
        QFile file(QDir::homePath() + "/file.txt");
        if (!file.open(QIODevice::ReadOnly | QIODevice::Text )) {
            qDebug() << file.errorString();
            return QString();
        }

        return QString::fromLatin1(file.readAll());
    }
};

int main()
{
    fileOperation fo;
    fo.write('a');
    qDebug() << fo.read();
    return 0;
}

主程序

TEMPLATE = app
TARGET = main
QT = core
SOURCES += main.cpp

构建并运行

qmake && make && ./main
于 2014-10-25T01:20:38.203 回答