简体   繁体   English

直接调用该函数有效,但是从另一个函数调用失败

[英]Calling the function directly works but calling from another function fails

When I use the display_menu function to call read_txt_file() it doesn't work. 当我使用display_menu函数调用read_txt_file()它不起作用。 I am unable to get the file contents to the stdout but when I use the read_txt_file() directly, it works. 我无法将文件内容输出到标准输出,但是当我直接使用read_txt_file() ,它可以工作。 I can see the contents of the file in stdout. 我可以在stdout中看到文件的内容。 What is the problem with the display_menu? display_menu有什么问题?

#include <stdio.h>
typedef struct filename
{
        int age;
        char name[100];
}name_t;

name_t * fname=NULL;

void quit()
{
      printf("\nPress enter to exit");
      fflush(stdin);
      getchar(); 
}

enter(char prompt[])
{
      puts(prompt);
      fflush(stdin);
      getchar(); 
}      

void read_txt_file()
{   
    char ch;   
    fname=(name_t *)malloc(sizeof(name_t));
    FILE *fptr=NULL;
    atexit(quit);
    printf("Please enter the file name to read : ");
    fflush(stdin);
    scanf("%s",fname->name);
    fptr=fopen(fname->name,"r");
    if(fptr == NULL)
    {
            perror("Could not open the file ");
            return;
    }
    printf("+++++++++++++++++++++++++++++++++++++++++++++++++");
    printf("Contents of the file %s are : ",fname->name);
    **while(ch != EOF)
    {
            ch=fgetc(fptr);
            printf("%c",ch);
    }** 
    enter("press enter");
    fclose(fptr);       
}

display_menu()
{
  int choice;
  while(1)
  {
        system("cls");
        printf("\t\t1.read and display from a file\n \
                \b2.quit\n");
                scanf("%d",&choice);
        switch(choice)
        { 
                      case 1 :
                           read_txt_file();
                           break;
                      case 2 :
                           exit(0);
                      default :
                              printf("please enter proper choice(1-3)\n Enter to continue");
                              fflush(stdin);
                              getchar();
        }
   }

}


int main()
{
   /*
   read_txt_file();
   */
   **display_menu();**
   return 0;
}

After the scanf("%d",&choice); 在scanf(“%d”,&choice);之后; call, the input will still have a '\\n' (the one of the return you pressed to enter the choice). 调用时,输入仍将带有“ \\ n”(您按下以输入选项的返回值之一)。 So the file name will be empty. 因此,文件名将为空。 You can add a getchar() after reading the choice (to remove the '\\n'). 您可以在读取选项后添加getchar()(以删除“ \\ n”)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM