【发布时间】:2021-05-13 11:50:26
【问题描述】:
我正在尝试将几行写入文件。写完行后,当我尝试使用fscanf 从文件中读取这些行时,它会进入无限循环。 fprintf 正在工作,但 fscanf 将进入无限循环。
#include<stdio.h>
#include<stdlib.h>
void main()
{
FILE *fp;
int roll;
char name[25];
float marks;
char ch;
fp = fopen("file.txt","w");
if(fp == NULL)
{
printf("\nCan't open file or file doesn't exist.");
exit(0);
}
do
{
printf("\nEnter Roll : ");
scanf("%d",&roll);
printf("\nEnter Name : ");
scanf("%s",name);
printf("\nEnter Marks : ");
scanf("%f",&marks);
fprintf(fp,"%d%s%f",roll,name,marks);
printf("\nDo you want to add another data (y/n) : ");
ch = getche();
}while(ch=='y' || ch=='Y');
printf("\nData written successfully...");
printf("\nData in file...\n");
while((fscanf(fp,"%d%s%f",&roll,name,&marks))!=EOF)
printf("\n%d\t%s\t%f",roll,name,marks);
fclose(fp);
}
【问题讨论】:
-
打印有用的错误消息,将它们写入标准错误,并在致命错误时退出非零。例如:
const char *path = "file.txt"; fp = fopen(path,"w"); if(fp == NULL) { perror(path); exit(EXIT_FAILURE); } -
永远不要使用
%s,其最大字段宽度最多小于要写入的缓冲区大小一倍。例如scanf("%24s",name); -
您已打开文件进行写入。为什么你期望
fscanf能够工作?