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; }
相关文章推荐
- 做技术注意,操作一个步骤,永远不要相信以前的经验,因为你面临的环境可能已经发生变化,但是没有人告诉你.
- 做技术注意,操作一个步骤,永远不要相信以前的经验,因为你面临的环境可能已经发生变化,但是没有人告诉你.
- 找出一个二维数组中的“鞍点”,即该位置上的元素在该行中 最大,在该列中最小(也可能没有“鞍点”),打印有关信息。(提示:注意特 殊情况:没鞍点或多个鞍点)
- 今天在Mac机器上使用了Flex Builder编辑了一个源代码文件,保存后使用vim命令去打开时发现系统自动在每一行的结尾添加了^M符号,其实^M在Linux/Unix中是非常常见的,也就是我们在Win中见过的/r回车符号。由于编辑软件的编码问题,某些IDE的编辑器在编辑完文件之后会自动加上这个^M符号。看起来对我们的源代码没有任何影响,其实并不然,当我们把源代码文件Check In到svn之类
- (转)在.NET程序运行过程中,什么是堆,什么是栈?什么情况下会在堆(栈)上分配数据?它们有性能上的区别吗?“结构”对象可能分配在堆上吗?什么情况下会发生,有什么需要注意的吗?
- 一次生日Party可能有p人或者q人参加,现准备有一个大蛋糕.问最少要将蛋糕切成多少块(每块大小不一定相等),才能使p人或者q人出席的任何一种情况,都能平均将蛋糕分食
- 找出一个二维数组中的"鞍点",即该位置上的元素在该行中最大,在该列中最小(也可能没有"鞍点"),打印有关信息.(提示:注意特殊情况:没鞍点或多个鞍点)
- JAVA编写的浏览器,在别人的基础上做了些许修改,实现了前进,后退,刷新功能,添加了一个搜索框,具体情况在运行结果中的文件-->注意中
- unix 环境高级编成 程序清单1-1 列出一个目录中所有的文件
- 有关对象流写入读取文件的一个细节
- UNIX环境高级编程学习——列出一个目录中的所有文件
- UNIX环境高级编程学习之第六章系统数据文件和信息 用链表的形式读出一个服务器的远程用户登入登出信息
- hdu2049 不容易系列之(4)——考新郎 错排+组合 一共有N对新婚夫妇,N个新娘随机坐成一排,每个新郎只能选一个, 其中有M个新郎找错了新娘,求发生这种情况一共有多少种可能.
- 将元数据写入文件“.dll”时发生错误 --“存储空间不足,无法完成此操作。
- FindFirstChangeNotification,创建一个文件通知对象,该对象用于监视文件系统发生的变化
- 【PHP】在php文件上传时需要注意的几个细节
- 记事 当sprintf的可变参数指向一个很长的字符串时,有可能没有将全部的字符串写入目标字符串。
- 一个表空间有多个数据文件,新增数据时的写入顺序和分配算法初探实验(下)_1
- windows已在xxx.exe中触发一个断点,其原因可能是堆被损坏,这说明xx.exe中或它所加载的任何DLL中有bug。
- 点击VS2010解决方案中的某个项目的任意一个文件导致VS开发环境关闭