初学者的问题:c语言中链表写入文件的问题(为什么我只能写如最后一个节点的数据)???

kaz33 2008-04-20 11:24:32
小弟刚来社区分数不多,恳请请高手指点指点!!!!!!!这是我的代码,我想把每个节点都存储到文件里,为什么只能存最后一个的??请说具体一点的步骤,该怎么做,谢谢各位啦!!!!!!!!!!!!!
#include <stdio.h>
#include <string.h>

struct student
{
char num[4];
char name[4];
student* next;
};

void printFile(char* desFile,student* p)
{
FILE* pFile=fopen(desFile,"w");
fprintf(pFile,"%s,%s\n",p->num,p->name);
fclose(pFile);
}

student* head=NULL;

void createLine(char* num,char* name)
{
student* newp=new student;
strcpy(newp->num,num);
strcpy(newp->name,name);
newp->next=NULL;
printFile("d:\\student.txt",newp);

if(head==NULL)
{
head=newp;
}
else
{
newp->next=head;
head=newp;
}
}

void printLine()
{
student* temp=head;
while(temp!=NULL)
{
printf("%s %s\n",temp->num,temp->name);
temp=temp->next;
}
}

void main()
{
char num[4];
char name[4];
for (int i=0; i<3; i++)
{
scanf("%s %s",num,name);
createLine(num,name);
}
printLine();
}
...全文
337 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
kaz33 2008-04-23
  • 打赏
  • 举报
回复
谢谢各位前辈指点!!!
一楼和三楼回答比较详细,不过一楼最先答,也谢谢五楼的补充,分数不多,请多多包涵,呵呵!!!!
candy110 2008-04-21
  • 打赏
  • 举报
回复
追加点知识:
摘自MSDN:
希望对你有用.

FILE *fopen(
const char *filename,
const char *mode
);

The character string mode specifies the type of access requested for the file, as follows:

"r"
Opens for reading. If the file does not exist or cannot be found, the fopen call fails.

"w"
Opens an empty file for writing. If the given file exists, its contents are destroyed.

"a"
Opens for writing at the end of the file (appending) without removing the EOF marker before writing new data to the file; creates the file first if it doesn't exist.

"r+"
Opens for both reading and writing. (The file must exist.)

"w+"
Opens an empty file for both reading and writing. If the given file exists, its contents are destroyed.

"a+"
Opens for reading and appending; the appending operation includes the removal of the EOF marker before new data is written to the file and the EOF marker is restored after writing is complete; creates the file first if it doesn't exist.

lala_benben 2008-04-21
  • 打赏
  • 举报
回复
...应该追加写
c_spark 2008-04-21
  • 打赏
  • 举报
回复
lz使用fopen时文件打开的方式不对,如果想保留文件原有的记录应该使用"a",而不是"w",会将原文件值清空并重写
void printFile(char* desFile,student* p)
{
FILE* pFile=fopen(desFile,"w"); //FILE* pFile=fopen(desFile,"a");这样就行了...
fprintf(pFile,"%s,%s\n",p->num,p->name);
fclose(pFile);
}
Leejun527 2008-04-20
  • 打赏
  • 举报
回复
你将FILE* pFile放在函数外,作为全局变量,将pFile=fopen(desFile,"w");和fclose(pFile);放在mian函数里。 只在函数中保留fprintf(pFile,"%s,%s\n",p->num,p->name);就可以了。
Leejun527 2008-04-20
  • 打赏
  • 举报
回复
void printFile(char* desFile,student* p) 
{
FILE* pFile=fopen(desFile,"w");
fprintf(pFile,"%s,%s\n",p->num,p->name);
fclose(pFile);
}

问题出在这个函数这,每次调用这个函数执行fopen(desFile,"w");时就会将desfile里面的值清空,重写。所以里面永远写的是最后一个student的内容。

69,373

社区成员

发帖
与我相关
我的任务
社区描述
C语言相关问题讨论
社区管理员
  • C语言
  • 花神庙码农
  • 架构师李肯
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧