c++ - Qt 创造者。从文件中读取并在 beaggleboard 上打印出来

标签 c++ linux qt beagleboard unistd.h

我正在使用 Qt Creator 做一个项目。 我有 3 个屏幕,每个屏幕有 4 个按钮。当单击第一个按钮时,它会将 0 写入文件(char),依此类推到 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);
}

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

最佳答案

您的代码存在多个问题:

  • 函数名很奇怪

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

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

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

  • 您在关闭系统调用中不一致地使用了 :: 前缀,但在其余部分没有。

  • 即使打开不成功,您仍在尝试关闭。

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

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

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

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

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

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

我个人会扔掉您的代码并改用这个代码:

main.cpp

#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

关于c++ - Qt 创造者。从文件中读取并在 beaggleboard 上打印出来,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26554879/

相关文章:

c++ - 加快图像中的自相似性

linux - 为什么 nginx 的性能比 apache httpd 服务器更好?

linux - 在 Linux 中删除 10 天前的旧文件夹

python - 为什么我的 QStandardItemModel itemFromIndex 方法返回 None? (索引无效)

android - QT Widget 使用 OpenCV 错误部署到 Android

c++ - QT 和 Crypto++ with/MTd

c++ - TCP recvfrom() 不存储 'from'

c++ - 使用 libpcap 读取数据包

linux - 将使用 "-g"编译的二进制文件与没有 "-g"的库链接

python - Qt4 : Write a function that creates a dialog and returns the choice of the user