赞
踩
O_TRUNC含义:
当文件存在时,将文件内容长度制定为0,与文件写入模式一起使用,可以达到覆盖写入的作用!
一下面这段文件复制的C代码为例:
- //copy.c 复制文件
- #include <sys/types.h>
- #include <sys/stat.h>
- #include <fcntl.h>
- #include<stdio.h>
- #include <unistd.h>
- int main(int argc,char** arg)
- {
- int file_old;
- int file_new;
- char rbuff[1024];
- int len;
- //argument num isn't enougth
- if(argc<3)
- {
- printf("usage: %s <old_filepath> <new_filepath>\n",arg[0]);
- return -1;
- }
- // step 1 open new file if successful will return a file ID("fd") else return -1
- file_old = open(arg[1],O_RDONLY);
- if(file_old<0)
- {
- printf("can't open file : %s\n",arg[1]);
- return -1;
- }
- //step 2 create or open new file
- //if want to write or read new file ,we need config its access mode
- file_new = open(arg[2],O_RDWR|O_CREAT|O_TRUNC,00664);//00 XXX与chmod xxx的权限类似
- if(file_new<0)
- {
- printf("can't create or open new file : %s\n",arg[2]);
- }
- //step 3 read old file and write to new file
- while((len=read(file_old,rbuff,1024))>0)//read old file
- {
- if(write(file_new,rbuff,len)!=len)
- {
- printf("can not write %s\n",arg[2]);
- } //write to new file
- }
- //step 4 close file ,use " open" must use "close"
- close(file_old);
- close(file_new);
- return 0;
-
- }
将代码放到Linux系统下的文件目录,在终端通过gcc编译指令生成可执行应用文件copy:
gcc -o copy copy.c
随后执行:
./copy copy.c copy2.c
此时,copy.c的内容将被复制到copy2.c当中,copy2.c的内容如下:
- //copy from copy.c
- #include <sys/types.h>
- #include <sys/stat.h>
- #include <fcntl.h>
- #include<stdio.h>
- #include <unistd.h>
- int main(int argc,char** arg)
- {
- int file_old;
- int file_new;
- char rbuff[1024];
- int len;
- //argument num isn't enougth
- if(argc<3)
- {
- printf("usage: %s <old_filepath> <new_filepath>\n",arg[0]);
- return -1;
- }
- // step 1 open new file if successful will return a file ID("fd") else return -1
- file_old = open(arg[1],O_RDONLY);
- if(file_old<0)
- {
- printf("can't open file : %s\n",arg[1]);
- return -1;
- }
- //step 2 create or open new file
- //if want to write or read new file ,we need config its access mode
- file_new = open(arg[2],O_RDWR|O_CREAT|O_TRUNC,00664);//00 XXX与chmod xxx的权限类似
- if(file_new<0)
- {
- printf("can't create or open new file : %s\n",arg[2]);
- }
- //step 3 read old file and write to new file
- while((len=read(file_old,rbuff,1024))>0)//read old file
- {
- if(write(file_new,rbuff,len)!=len)
- {
- printf("can not write %s\n",arg[2]);
- } //write to new file
- }
- //step 4 close file ,use " open" must use "close"
- close(file_old);
- close(file_new);
- return 0;
-
- }
假设我们此时有一个1.txt文件,其内容为:
HELLO WORLD,I AM 1.txt
再次执行:
./copy 1.txt copy2.c
copy2.c的内容将被覆盖为
Hello World,I am 1.txt
若无添加O_TRUNC选项,则只会覆盖一部分文件内容,此时,copy2.c的内容如下:
总结:
O_TRUNC可以在打开文件的时候,将文件的内容长度设置为0,并于文件写入一同使用,达到覆盖写入的效果。
题外:若要实现追加写入,则使用选项O_APPEND
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。