先说结论:
追加模式下打开文件时:
- lseek可以改变当前文件偏移量
- 写的起始位置始终位域文件末尾, 当前文件偏移量的改变并不会影响文件写
- 读会出错, 出错信息为: bad file descriptor, 因为文件时只读并追加模式打开
实验过程
实验代码:
#define BUFSIZE 100
int main(){
//执行命令: 0>>read.txt 0号文件描述符追加方式打开read.txt, 看是否可以使用lseek在任意位置读写
//查看0号文件描述符的初始偏移量
fprintf(stdout,"at the beginning, offset of 0 is %d\n",lseek(0,0,SEEK_CUR));
//偏移0号文件描述符到初始位置
if(lseek(0,2,SEEK_SET) == -1){
fprintf(stdout,"lseek() failed.\n");
}
fprintf(stdout,"lseek() makes the 0 offset 2 bytes from the begin of the file.\n");
//查看0号文件描述符的偏移量
fprintf(stdout,"after lseek(), offset of 0 is %d\n",lseek(0,0,SEEK_CUR));
char buf[BUFSIZE]="";
//从0号文件里读
if(read(0,buf,BUFSIZE) == -1){
fprintf(stdout,"read() failed: %s\n", strerror(errno));
}
fprintf(stdout,"buf = %s\n",buf);
char *str = "123456";
//往0号文件里写
if(write(0,str,strlen(str)) == -1){
fprintf(stdout,"read() failed.\n");
}
fprintf(stdout,"write %s into 0\n",str);
close(0);
exit(0);
}
实验结果:
结果分析:见上面的结论