c语言文件读写问题

2026年09月03日 11:46
有3个网友回答
网友(1):

你的意思大概是说如果没有C:\1.txt
这个文件的话
系统就会抛出异常,对吧
你可以这样处理
#include
#include

#define NULL 0
struct stu_type
{
int num;
char name[10];
}stu[3];

void read()
{
FILE *fp;
int i;
if((fp=fopen("C:\\1.txt","rb"))!=NULL)
{
printf("hello\n");
for(i=0;i<3;i++)
{
fread(&stu[i],sizeof(struct stu_type),1,fp);
printf("%d\t%s\n",stu[i].num,stu[i].name);
}
}
else
printf("false\n");
if(fp != NULL )
fclose(fp);
}

void main()
{
read();

}

因为如果没有初始化fp指针的话,就无法对它进行任何操作(包括fclose(fp);)
read函数的最后几句你也可以改成
else {
printf("false\n");
exit(1);
}

网友(2):

你定义了两个一样的头文件!!!

网友(3):

你的C:\1.txt文件里面内容是什么?