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. }  

相关内容