0

我正在尝试打开位于不同目录中的文件,但我总是收到错误消息。我的代码如下所示:

#include <stdio.h>   
#include <stdlib.h>

int main()
  {
  FILE *file;
  char file_name[25];

  printf("What file do you want? ");
  scanf("%s", file_name);
  file = fopen("Dir1/Dir2/file_name","r"); 

  if( file == NULL ) 
  {
    printf("There is no file by that name\n");
    exit;
 }

我怀疑问题出在“fopen”部分。如果我输入文件名(例如 file =fopen ("Dir1/Dir2/list.txt", "r") 那么它将起作用。但是,我希望用户输入文件名。任何帮助将不胜感激。 谢谢!

4

1 回答 1

1

您的代码尝试打开名为“file_name”的文件。我想你的意思是:

#include <stdio.h>   
#include <stdlib.h>

int main()
{
  FILE *file;
  char file_name[25];
  char path[80];

  printf("What file do you want? ");
  scanf("%s", file_name);
  snprintf(path, sizeof(path), "Dir1/Dir2/%s", file_name);
  // printf("Opening file %s\n", path);
  file = fopen(path,"r"); 

  if( file == NULL ) 
  {
    printf("There is no file by that name\n");
    exit;
  }
于 2013-10-27T09:09:30.230 回答