歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux基礎 >> Linux教程

Unix環境寫入文件時要注意小細節

Unix環境寫入文件時,要注意的一個小細節,要不任何情況都有可能發生。

在Unix/Linux環境下,寫入文件時。如果,在open函數的讀寫模式,只提供了,讀寫、如果不存在生成,這些模式時。

如果源文件存在,以非追加的方式寫入數據時,當後續的數據長度大於源文件已有的數據時,後續的文件覆蓋以前的數據。

如果後續的數據長度小於源文件以後的數據長度時,只是覆蓋了後續寫入的數據長度。這時,文件的數據時,兩者的混合,這不是我們想要的。

所以為了數據的正確性,在以非追加(append)方式吸入數據時,首先要清空,要寫入的文件。

以下為一個例子:

  1. #include<stdio.h>   
  2. #include<stdlib.h>   
  3. #include<fcntl.h>   
  4. int main(int argc ,char * argv[])   
  5. {      
  6.     int val = 0;   
  7.     int fd = 0;   
  8.     char* fpath = "./test.txt";   
  9.     char buffer[] = "Hi i am harry.";   
  10.     char buffer1 []= "liyachao.";   
  11.     /*open the file with write/read and create module*/  
  12.     fd = open(fpath,O_RDWR|O_CREAT);   
  13.     /*truncate the exiting file's size to zero,meanning empty the exit file.*/  
  14.     ftruncate(fd,0);   
  15.     val = write(fd,buffer,strlen(buffer));   
  16.     printf("wirte %d bytes.",val);   
  17.       
  18.     return 0;   
  19. }  
Copyright © Linux教程網 All Rights Reserved