为什么我使用ftruncate截断文件后文件大小确实改变了,但是用read读取文件的内容还是截断之前的呢?
int main(void)
{
//创建文件
int new_fd = open("file/a",O_RDWR|O_CREAT|O_EXCL,0644);
if(-1==new_fd)
{
printf("%d: ",__LINE__-3);
perror("creat");
exit(-1);
}
//打开文件
int old_fd = open("file/file_test",O_RDWR);
if(-1==old_fd)
{
printf("%d: ",__LINE__-3);
perror("open");
exit(-1);
}
//复制文件
char buff[1024];
while(read(old_fd,buff,sizeof(buff)))
{
int res = write(new_fd,buff,strlen(buff));
if(-1==res)
{
printf("%d: ",__LINE__-3);
perror("write");
close(new_fd);
close(old_fd);
exit(-1);
}
memset(buff,sizeof(buff),0);
}
memset(buff,sizeof(buff),0);
close(old_fd);
//读出修改后的文件
lseek(new_fd,0,SEEK_SET);
while(read(new_fd,buff,sizeof(buff)))
{
printf("%s",buff);
memset(buff,sizeof(buff),0);
}
printf("\n\n");
//获得修改过后的文件的信息
struct stat st;
if(-1==fstat(new_fd,&st))
{
printf("%d: ",__LINE__-3);
perror("stat");
close(new_fd);
exit(-1);
}
printf("文件大小为%d\n",st.st_size);
printf("文件最后修改时间为%s",ctime(&st.st_mtime));
printf("文件权限为%o\n\n",st.st_mode&0777);
//截取前100个字节
if(-1==ftruncate(new_fd,100))
{
printf("%d: ",__LINE__-3);
perror("truncate");
close(new_fd);
exit(-1);
}
close(new_fd); //先关闭文件描述符
new_fd = open("file/a",O_RDWR);//再次打开
if(-1==new_fd)
{
printf("%d: ",__LINE__-3);
perror("creat");
exit(-1);
}
#ifdef DE
if(-1==fstat(new_fd,&st))
{
printf("%d: ",__LINE__-3);
perror("stat");
close(new_fd);
exit(-1);
}
printf("文件大小为%d\n",st.st_size);
printf("文件最后修改时间为%s",ctime(&st.st_mtime));
printf("文件权限为%o\n\n",st.st_mode&0777);
#endif
//读出文件
memset(buff,sizeof(buff),0);
lseek(new_fd,0,SEEK_SET);
while(read(new_fd,buff,sizeof(buff)))
{
printf("%s",buff);
memset(buff,sizeof(buff),0);
}
printf("\n\n");
//改变新建文件的权限
close(new_fd);
remove("file/4_file");
return 0;
}