首页 > 解决方案 > 要求用户输入文件名。并且在循环中比要求用户写入和关闭文件。在 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);


}

标签: c

解决方案


你可能想要这个:

#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并且后面的语句将一遍又一遍地执行。

是的,请阅读对您问题的评论。


推荐阅读