您的位置:首页 > Web前端

Unix环境写入文件时,要注意的一个小细节,要不任何情况都有可能发生

2011-03-10 21:44 453 查看
 

 在Unix/Linux环境下,写入文件时。如果,在open函数的读写模式,只提供了,读写、如果不存在生成,这些模式时。

    如果源文件存在,以非追加的方式写入数据时,当后续的数据长度大于源文件已有的数据时,后续的文件覆盖以前的数据。

    如果后续的数据长度小于源文件以后的数据长度时,只是覆盖了后续写入的数据长度。这时,文件的数据时,两者的混合,这不是我们想要的。

    所以为了数据的正确性,在以非追加(append)方式吸入数据时,首先要清空,要写入的文件。

   以下为一个例子:
#include<stdio.h>
#include<stdlib.h>
#include<fcntl.h>
int main(int argc ,char * argv[])
{
int val = 0;
int fd = 0;
char* fpath = "./test.txt";
char buffer[] = "Hi i am harry.";
char buffer1 []= "liyachao.";
/*open the file with write/read and create module*/
fd = open(fpath,O_RDWR|O_CREAT);
/*truncate the exiting file's size to zero,meanning empty the exit file.*/
ftruncate(fd,0);
val = write(fd,buffer,strlen(buffer));
printf("wirte %d bytes.",val);

return 0;
}
 
 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  unix buffer file module
相关文章推荐