Linux下對臨時檔案的操作之mkstemp

來源:互聯網
上載者:User

   使用臨時檔案要考慮幾個問題:

  保證臨時檔案間的檔案名稱不互助衝突。

  保證臨時檔案中內容不被其他使用者或者駭客偷看、刪除和修改。

  Linux中提供了mkstemp 和 tmpfile 函數來處理臨時檔案。

  mkstemp函數

  int mkstemp(char *template);

  mkstemp函數在系統中以唯一的檔案名稱建立一個檔案並開啟,而且只有目前使用者才能訪問這個臨時檔案,並進行讀、寫操作。mkstemp函數只有一個參數,這個參數是個以“XXXXXX”結尾的非Null 字元串。mkstemp函數會用隨機產生的字串替換“XXXXXX”,保證了檔案名稱的唯一性。 函數返回一個檔案描述符,如果執行失敗返回-1。在glibc 2.0.6 以及更早的glibc庫中這個檔案的存取權限是0666,glibc 2.0.7以後的庫這個檔案的存取權限是0600。

  臨時檔案使用完成後應及時刪除,否則臨時檔案目錄會塞滿垃圾。由於mkstemp函數建立的臨時檔案不能自動刪除,所以執行完mkstemp函數後要調用unlink函數,unlink函數刪除檔案的目錄入口,但臨時檔案還可以通過檔案描述符進行訪問,直到最後一個開啟的進程關閉檔案操作符,或者程式退出後臨時檔案被自動徹底地刪除。

  #include

  #include

  #include

  #include

  int write_temp_file(char* buffer,size_t length) {

  int len=length;

  char filename_template[]="/tmp/temp_file.XXXXXX";

  int fd=mkstemp(filename_template);

  unlink(filename_template);//Unlink the file, so it'll be removed when close

  printf("Template file name:%sn",filename_template);

  write(fd,&len,sizeof(len));

  write(fd,buffer,len);

  return fd;

  }

  char* read_temp_file(int fd, size_t* length) {

  char* buffer;

  lseek(fd,0,SEEK_SET);

  read(fd,length,sizeof(size_t));

  buffer=(char*)malloc(*length);

  read(fd,buffer,*length);

  close(fd); // Temp file will be deleted

  return buffer;

  }

  int main(int argc, char** argv) {

  char buffer[]="Test template files";

  int fd=write_temp_file(buffer,strlen(buffer));

  int len=0;

  char* result=read_temp_file(fd,&len);

  printf("Len:%dnContent:%sn",len,result);

  free(result);

  return 0;

  }

  tmpfile函數

  如果您使用C library I/O函數,並且並沒有另一個程式使用這個臨時檔案,有個更簡潔的函數——tmpfile。tmpfile函數建立並開啟一個臨時檔案,並且自動執行了unlink。tmpfile函數返回一個檔案描述符,如果執行失敗返回NULL。當程式執行了fclose或者退出時,資源被釋放。

  另外,linux系統中還提供mktemp、 tmpnam、 和tempnam等函數,但是由於健壯性和安全性的問題,不建議使用。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.