c - 要求用户输入文件名。并且在循环中比要求用户写入和关闭文件。在 c
问题描述
我正在尝试从用户的输入中打开一个文本文件。在循环中要求用户写。如果用户键入 0,则程序结束。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(){
char filename[50];
FILE* fpointer;
printf ("Please Enter the File Name: ");
scanf ("%s",&filename);
fpointer = fopen(filename,"r");
在这里,我需要一个循环来要求用户写入文件,直到用户输入 0 来结束程序。
if (filename == 0)
{
getch();
exit(1);
}
filename(close);
}
解决方案
你可能想要这个:
#include <stdio.h>
#include <stdlib.h>
int main()
{
char filename[50];
FILE *fp;
int check = 1;
while(check)
{
printf("Enter name of the file or path: ");
scanf("%50s", filename);
if(!(fp = fopen(filename, "r")))
{
fprintf(stderr, "Can't open the file.\n");
exit(-1);
}
// file reading statements...
fclose(filename);
printf("Do you want to continue(1 to continue/0 to exit): ");
scanf(" %d", &check);
}
}
这里我们声明一个int
变量check
来退出循环。在while
循环内部,如果check
最后的值被更新,scanf
那么它将导致退出循环,否则我们将继续请求filename
并且后面的语句将一遍又一遍地执行。
是的,请阅读对您问题的评论。
推荐阅读
- javascript - 单个承诺的多个侦听器
- python - 将字典键设为行,将 dict 值设为列,一个值作为列名,一个作为列值
- angular - Angular 11:如何从多个组件共享的服务中获取对 Reactive Form 的更新
- python - 在 PyQt5 中按下特定键盘按键时将焦点放在特定的 QLineEdit 上?
- angular - 如果在 mat-date-range-picker 中禁用日期,如何禁用范围选择
- python - Networkx 邻接矩阵条件
- android - 以编程方式在清单中设置 android 查询以声明包名称
- python - 保存为多个numpy文件时如何连接keras history.history文件?
- php - 一年中的最后一周和 1 月 1 日与 Carbon?
- xml - 从另一个 RML 文件中引用 RML 部分