- 論壇徽章:
- 3
|
朋友真是一針見血啊 {:3_182:}
第一點(diǎn) 至少creat第二個參數(shù)是不能填O_RDWR的. 的確是我疏忽了,這個老接口被后來的OPEN給兼容了,我以為參數(shù)也是一致的^_^
第二點(diǎn) 我更沒留意了,嘿
原因找出來了,應(yīng)該就是因?yàn)閏reat返回的FD是只寫的,對于讀接口來說是非法的,所以如果為讀專門open一次,返回一個供read的FD,應(yīng)該就沒問題了。總之是由于讀寫共用一個FD,搞混亂了。。。如果在之前的基礎(chǔ)上稍微改一下,應(yīng)該還是行得通的 嘿
int fd,byteswrite,bytesread;
char buf[256];
int length;
memset(buf,0,256);
strcpy(buf,"hello ,this is a test" ;
length = strlen(buf);
// fd = creat("test.txt", S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH);
fd = open("test.txt",O_CREAT|O_TRUNC|O_RDWR,0666);
byteswrite = write (fd,buf,length);
printf("byteswrite is %d \n",byteswrite);
if(fsync(fd)==-1)
printf("fsync error\n" ;
struct stat stat_buf;
int ret;
ret = fstat(fd,&stat_buf);
if(ret == -1){
printf("%s \n",strerror(errno));
exit(1);
}
memset(buf,0,256);
printf(" fd : %d \n",fd);
//close(fd);
//fd = open("test.txt",O_RDWR,0);
int offset;
offset = lseek(fd,0,SEEK_CUR);
printf(" offset : %d \n",offset);
offset = lseek(fd,(-1)*offset,SEEK_CUR);
if(offset == -1){
printf("%s \n",strerror(errno));
exit(1);
}
bytesread = read(fd,buf,length);
if(bytesread == -1){
printf("%s \n",strerror(errno));
exit(1);
}
printf("bytesread is %d \n",bytesread);
printf("read result is %s\n",buf);
多謝朋友指正 |
|