- 读取(open)文件并写入(write)另一个文件
#include <stdio.h> #include<stdlib.h> #include<string.h> #include<fcntl.h>.h> int main() { int fd1=open("/home/cpc/Documents/diary",O_RDWR); printf("%d\n",fd1); int fd2=open("/home/cpc/Documents/anothernote",O_WRONLY|O_CREAT,0664); char buf[4096]; int len=read(fd1,buf,sizeof(buf)); while(len>0) { write(fd2,buf,len); len=read(fd1,buf,sizeof(buf)); } return 0; }
- lseek动态扩展文件
#include <stdio.h> #include<stdlib.h> #include<string.h> #include<fcntl.h>.h> int main() { int fd1=open("/home/cpc/Documents/diary",O_RDWR|O_CREAT,0664); if(fd1==-1) { perror("file read error"); exit(1); } lseek(fd1,1000,SEEK_END);//让指针扫荡到文件末尾,再偏移1000个字节,实际上就是动态扩展 return 0; }
.......然而通过linux shell命令ll查看文件信息,文件大小并未改变
.......原来还得添加一个字符作为收尾
#include <stdio.h> #include<stdlib.h> #include<string.h> #include<fcntl.h>.h> int main() { int fd1=open("/home/cpc/Documents/diary",O_RDWR|O_CREAT,0664); if(fd1==-1) { perror("file read error"); exit(1); } lseek(fd1,1000,SEEK_END); write(fd1,"c",1); close(fd1); return 0; }
原文地址:https://www.cnblogs.com/saintdingspage/p/12154527.html
时间: 2024-11-06 17:03:32