FILE fp; long cnt=0; char c,filename[20]; void createfile(); createfile(); scanf("%s",filename); fp=fopen(filename,"w"); while(feof(fp))
时间: 2024-03-02 08:53:38 浏览: 17
在这段代码中,存在以下错误:
1. `FILE fp;`应该修改为`FILE *fp;`,因为`fopen`函数返回的是一个指向`FILE`类型的指针。
2. `while(feof(fp))`应该修改为`while(!feof(fp))`,因为`feof`函数在文件读取结束后返回非0值,因此需要取反。
3. `void createfile(); createfile();`应该放在`main`函数之外,或者在`main`函数内先声明再调用该函数。
修改后的代码如下所示:
```c
#include <stdio.h>
void createfile();
int main()
{
FILE *fp;
long cnt = 0;
char c, filename[20];
createfile(); // 调用函数创建文件
scanf("%s", filename);
fp = fopen(filename, "r");
if (fp == NULL) { // 判断文件是否打开成功
printf("文件打开失败!\n");
return 0;
}
while (!feof(fp)) {
c = fgetc(fp);
if (c >= '0' && c <= '9') {
cnt++;
}
}
printf("%ld", cnt);
fclose(fp);
return 0;
}
void createfile()
{
FILE *fp;
fp = fopen("test.txt", "w");
fprintf(fp, "1 2 3\n");
fprintf(fp, "4 5 6\n");
fprintf(fp, "7 8 9\n");
fclose(fp);
}
```
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)