在qt中创建临时文本文件 [英] Creating temporary text file in qt

查看:511
本文介绍了在qt中创建临时文本文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在QT中创建一个临时文本文件,然后在程序结束时将其删除。我有两个线程(T1,T2)。 T1需要在TEMP文件中写入文本,并且T2将连续读取它。我还需要继续跟踪文件指针。我没跟谷歌好运。



你能告诉我怎么去吗?



*注意,我不是专业人士,所以请尽量让它尽可能简单。



我尝试了什么:



我已经完成了这一切,只需编写文本文件而不是稍后阅读。但这是创建问题现在解决问题的方法是生成临时文件。但是不知道如何将文本写入TEMP文件以及如何获取文本。

I'm trying to create a temporary text file in QT and then delete it at the end of the program. I have two threads(T1, T2). T1 need to write the text in TEMP file and and T2 will read it continuously. I need to keep tracking the file pointer as well. I haven't had much luck with Google.

Could you tell me how to go for it?

*NOTE, i'm not a professional, so please bear the pain of making it as simple as possible

What I have tried:

I had done this all with writing the text file and than reading it later. But this is creating problem now solution for the problem is generate the Temporary file. But dont know how to write text into TEMP file and how to fetch text.

推荐答案

当多个线程应该访问同一个对象时,必须使用锁定。对于临时文件的情况,我将创建一个封装所有必要操作的类(包括在析构函数中删除文件)。



示例(使用C库 FILE object和 QMutex Class | Qt Core 5.5 [ ^ ]锁定对象):

When multiple threads should access the same object you must use locking. For your case of a temporary file I would create a class that encapsulates all the necessary operations (including deleting the file in the destructor).

Example (using C library FILE object and QMutex Class | Qt Core 5.5[^] lock object):
// TempFile.h
#include <QMutex>
#include <stdio.h>

class TempFile
{
public:
    TempFile();
    ~TempFile();
    bool Open(const QString& fileName);
    void Close();
    int Read(char * data, int size);
    int Write(const char * data, int size);
protected:
    QString name;
    FILE *file;
    QMutex mutex;
    long pos;
};







// TempFile.cpp
#include "TempFile.h"
TempFile::TempFile()
{
    file = NULL;
    pos = 0;
}

TempFile::~TempFile()
{
    bool isOpen = file != NULL;
    Close();
    if (isOpen)
        unlink(QString::toLocal8Bit(name).data());
}

bool TempFile::Open(const QString& fileName)
{
    file = fopen(QString::toLocal8Bit(fileName).data(), "w+");
    name = fileName;
    return file != NULL;
}

void TempFile::Close()
{
    if (file)
        fclose(file);
    file = NULL;
    pos = 0;
}

int TempFile::Read(char * data, int size)
{
    mutex.lock();
    // Seek to read position
    fseek(file, pos, SEEK_SET);
    int read = fread(data, 1, size, file);
    if (read > 0)
        pos += read;
    mutex.unlock();
    return read;
}

int TempFile::Write(const char * data, int size)
{
    mutex.lock();
    // Seek to write position (end)
    fseek(file, 0, SEEK_END);
    int written = fwrite(data, 1, size, file);
    mutex.unlock();
    return written;
}


这篇关于在qt中创建临时文本文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆