如何propertly明确的文件在Linux

问题描述:

美好的一天,我打开文件写入到它下面的一些content.Code:如何propertly明确的文件在Linux

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可能)?

+1

您应该在构造函数中测试'open'的成功,并可能在失败时使用'perror'。 – 2013-03-21 06:42:56

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

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

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

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

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

+0

只有一个进程可以写入,但如果我使用具有lseek功能的线程,可能会增加写入速度? – 2013-03-21 06:42:20