首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C语言 >

Ubuntun上连续读写文件

2012-08-14 
Ubuntun下连续读写文件在Ubuntu下写了一个测试函数,使用c语言库函数中的文件操作函数进行读写,结果写的时

Ubuntun下连续读写文件
在Ubuntu下写了一个测试函数,使用c语言库函数中的文件操作函数进行读写,结果写的时候正常,读的时候提示bad file descrition,大致意思是错误的文件描述符。可我gdb调试的时候打印出来的文件描述符和前面fwrite的时候文件描述符一致,很郁闷为什么会这样了。高手帮忙看看吧。
 

C/C++ code
#include <stdio.h>  #include <string.h>int main(void){  FILE *fd; int ret; fd = fopen("test.txt","w"); if ( ret <0)      perror("open error");  char str[]="hi hero';  ret = fwrite(str,sizeof(char),strlen(str),fd);  if ( ret <0)      perror("write error");  ret = fseek(fd,0l,0);   if ( ret <0)      perror("seek error");  char str2[20]="";   ret = fread(str2,sizeof(char),strlen(str),fd);   if ( ret <=0)      perror("read error");  printf("%s",str2); return 0;}

  
fseek这一行加不加都会在fread的时候报错,另外如果在fwrite之后调用fclose之后,再次fopen打开,然后fread程序就可以正常工作了。很不理解,恳请高手指点一二。

[解决办法]
fd = fopen("test.txt","w");
"w":只能写,不能读
要想读”rw"
[解决办法]
"rb+"

[解决办法]
When the "r+", "w+", or "a+" access type is specified, both reading and writing are allowed (the file is said to be open for “update”). However, when you switch between reading and writing, there must be an intervening fflush, fsetpos, fseek, or rewind operation. The current position can be specified for the fsetpos or fseek operation, if desired.

热点排行