Unix環境寫入文件時,要注意的一個小細節,要不任何情況都有可能發生。
在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;
- }