Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/69.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
要求用户输入文件名。在in循环中,要求用户写入并关闭文件。在c中_C - Fatal编程技术网

要求用户输入文件名。在in循环中,要求用户写入并关闭文件。在c中

要求用户输入文件名。在in循环中,要求用户写入并关闭文件。在c中,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",&

我试图从用户的输入打开一个文本文件。在循环中,要求用户写入。如果用户键入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");

你可能想要这个:

#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 main()
{
字符文件名[50];
文件*fp;
整数检查=1;
while(检查)
{
printf(“输入文件名或路径:”);
scanf(“%50s”,文件名);
如果(!(fp=fopen(文件名,“r”))
{
fprintf(stderr,“无法打开文件。\n”);
出口(-1);
}
//文件读取语句。。。
fclose(文件名);
printf(“是否要继续(1继续/0退出):”;
scanf(“%d”和“检查”);
}
}
这里我们声明一个
int
变量
check
,以退出循环。在
内部,而
循环中,如果上次
scanf
中更新了
check
的值,那么它将导致退出循环,否则我们将继续请求
filename
,并将反复执行以下语句


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

文件名==0
相当于
文件名==NULL
,这永远不会是真的。另一方面,
&filename
对于
scanf
是错误的。由于
filename
是一个数组,因此
&filename
的类型是指向数组本身的指针,
char(*)[50]
。这不是
%s
格式所期望的类型,该格式需要
字符*
。您可以从
&filename[0]
中获取,也可以直接从
文件名中获取。格式和参数类型不匹配会导致未定义的行为。至于您的问题,
filename
是一个字符串。如果要检查用户是否输入了零,则需要与字符串
“0”
(使用
==
)进行比较。可能是
文件名(关闭)应为
fclose(fpointer)
或者您的意思是希望从用户处读取与文件分开的输入?然后,您需要读取用户的实际输入,并将其与正确的值进行比较。老实说,你似乎只是在瞎猜,什么都不知道。也许你需要后退几步,从一本像样的书(或课程)和基本的“hello world”类型的程序开始?
#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);
    }
}