如何正确清除文件在linux中

How propertly clear file in linux

本文关键字:linux 文件 何正确 清除      更新时间:2023-10-16

你好,我打开文件给它写一些内容。下列代码:

class file_worker
{
public:
    file_worker(const std::string &path):path_(path),stop_(false)
    {
        umask(0);
        file_descriptor_ = open(path_.c_str(),O_WRONLY|O_CREAT, 0666);
    }
    void operator()()
    {
        if(file_descriptor_!=-1)
        {
             clear_file();
            //write something
        }
    }
    void clear_file()
    {
    }
    ~file_worker()
    {
        if(file_descriptor_!=-1)
        {
            close(file_descriptor_);
        }
    }
private:
    const std::string path_;
    int file_descriptor_;
    bool stop_;
};

如何实现clear_file();函数,它将有可能清除(删除所有文件内容),而不关闭文件描述符?哪一种方式可以更快地写入文件?是否有可能在文件的不同部分同时写一些线程的文件(使用lseek可能)?

您没有定义清除文件对您意味着什么。

您可以将文件缩小到0大小,使用ftruncate(2)。

可以将文件中的所有字节归零。然后,对write(2)使用lseek(2)或者pwrite(2)

如果其他进程同时写入文件(这是不好的做法),可能会出现问题。

我不确定使用多线程真的会加速所有字节的归零。(这样做是磁盘密集型的,除非命中系统文件缓存,并且多线程不会加速磁盘),所以我将首先进行基准测试。