標籤:檔案讀寫 內容重複 linux
在Linux系統中,我們經常需要對問檔案進行操作,檔案的讀寫時又經常會出現各種各樣的問題。在這裡我就講一下我在進行檔案讀寫操作時遇到的問題。
背景:首先向檔案中寫入內容,然後從檔案中從後往前讀取檔案中的內容;
在Qt環境下的編程
代碼如下:
#include "mainwidget.h"
#include "ui_mainwidget.h"
#include<stdio.h>
#include<string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#define FILENAME "alamDetailList" //檔案名稱
#define ARRAYSIZE 200
typedef struct alarmMessage{
int msgSize; //資料大小
char mesInfo[ARRAYSIZE]; //資料內容
}msg_t;
void mainWidget::saveMessageToFile() //把內容寫入檔案中
{
int isFileExist = access(FILENAME,F_OK); //判斷檔案是否存在
int fd;
if (isFileExist == 0) //檔案存在
{
fd = open(FILENAME,O_WRONLY);
qDebug() <<"開啟檔案";
}else {
qDebug()<<"建立並開啟檔案";
fd = open(FILENAME,O_RDWR|O_CREAT,S_IRUSR|S_IWUSR);
}
if(fd == -1)
{
qDebug() << tr("開啟檔案失敗");
}
lseek(fd,0,SEEK_END); //每次寫入檔案之前,都移到檔案的最後的位置
//alarmMSGDeatil 是QString類型,也就是要寫入檔案中的內容,下面是將QString類型轉換為char *類型
const char *detailTime = alarmMSGDeatil.toStdString().c_str();
msg_t msg;
memset(msg.mesInfo,‘\0‘,sizeof(msg.mesInfo));
msg.msgSize = strlen(detailTime);
strcpy(msg.mesInfo,detailTime);
int bytesWrite = write(fd,&msg,sizeof(msg));
qDebug() << "==bytesWrite111=="<<bytesWrite;
::close(fd);
}
//讀取檔案內容,從後往前讀
void mainWidget::readFile()
{
qDebug("11111111111");
//ui->listWidget->setVisible(true);
int fd = open(FILENAME,O_RDONLY);
if(fd == -1)
{
qDebug() << "開啟檔案失敗";
return;
}
lseek(fd, 0 ,SEEK_END); //位置指向檔案的最後
off_t offset = 0;
int readBytes = 0;
//ui->listWidget->clear();
while(1) //通過死迴圈來完成檔案中所有內容的讀寫
{
offset += sizeof(msg_t);
qDebug() << "===offset=====" <<offset;
//得到當前位置距離檔案頭的距離
off_t curFromHead = lseek(fd, 0 - offset,SEEK_END);
if(curFromHead < 0) //如果不加上這一判斷的話,就會出現檔案中內容重複讀取 的情況
{
break;
}
//qDebug() <<"====curFromHead====" <<curFromHead;
msg_t readBuf;
readBytes = read(fd, &readBuf, sizeof(msg_t));
qDebug() <<"===readBytes===" << readBytes;
if(readBytes <= 0) //
{
qDebug() << "檔案讀取完成";
break;
}
QString timeString = QString(readBuf.mesInfo);
qDebug() << timeString;
// ui->listWidget->addItem(timeString);
readBytes = 0;
}
::close(fd);
qDebug()<<"222222";
}
Linux檔案讀寫之得到重複的內容