问题
I'm doing a project using Qt creator. I have 3 screen for every screen there are 4 button. when clicked on the first button it will wirte 0 to the file (char) and so on to 3. When i reach the last screen (4. screen) where i will read from the file and display the input from the buttons it doenst show the 3 chars.
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);
}
when i close the application and open it again with new inputs from button it shows the previous input in the last screen. Any suggestion or help to solve this problem.
回答1:
There are multiple issues with your code:
The function names are weird
You are not checking against errors after the write system call.
You are not checking against errors after the lseek system call.
You are not checking against errors after the close system call.
You inconsistently use the
::
prefix for the close system call, but not the rest.You are trying to close even if the open was unsuccessful.
You are trying to write 2 characters to the file, but then you are trying to read 4 characters back.
You have a left-over syncfs behind comment.
You hard-coded the home path instead of using some home variable.
You are trying to create a superfluous temporary variable "str" in the read.
You are trying to close after the return there.
Your code is very platform specific, whereas you already depend on Qt.
I would personally throw out your code and use this one instead:
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;
}
main.pro
TEMPLATE = app
TARGET = main
QT = core
SOURCES += main.cpp
Build and Run
qmake && make && ./main
来源:https://stackoverflow.com/questions/26554879/qt-creator-read-from-a-file-and-print-it-out-on-beaggleboard