读书人

fwrite()参数有关问题

发布时间: 2013-07-04 11:45:40 作者: rapoo

fwrite()参数问题求助
本帖最后由 nain001 于 2013-05-22 22:14:47 编辑

typedef struct student{
char number[11];
char name[11];
char sex;
int age;
}Item;

typedef struct node{
Item item;
struct node * next;
}Node;

typedef Node * List;


/*  将List写入文件  */
void WriteToFile(const List * plist,char * filename){
Node * pnode = *plist;
FILE * fp;
int count=0;
if((fp = fopen(filename,"w+b"))==NULL){
fprintf(stderr,"%s 无法打开!,写入文件失败.\n",filename);
exit(1);
}
while(pnode!=NULL){
fwrite(pnode->item,sizeof(Item),1,fp);//这行报错,参数不对,要怎么改呢?第一个参数不可以这样吗?
pnode = pnode -> next;
count++;
}
fclose(fp);
printf("有%d条记录被写入文件\"%s\"中.\n",count,filename);
}

[解决办法]
fwrite(&(pnode->item),sizeof(Item),1,fp);

应该是传递地址
[解决办法]
hi, dear friend.
i try to compile your code and print error message below:
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
test.c:29:9: error: incompatible type for argument 1 of ‘fwrite’
In file included from test.c:1:0:
/usr/include/stdio.h:717:15: note: expected ‘const void * __restrict__’ but argument is of type ‘Item’
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
size_t fwrite(const void *ptr, size_t size, size_t nmemb,
FILE *stream);
===base these info, can you understand the reason? (you pass a param pnode->item type is Item but the fwrite need accept a const void *)

to solve this problem change the code : Item item ----- Item * item


hope can help you !


yandriver8@gmail.com


[解决办法]
fwrite的原型是

size_t fwrite(const void* buffer, size_t size, size_t count, FILE* stream);

第一个参数要求传的是指针。。所以应该改为
fwrite(&pnode->item,sizeof(Item),1,fp);

读书人网 >C语言

热点推荐