【问题标题】:Why wont my file open and how can I fix it?为什么我的文件打不开,我该如何解决?
【发布时间】:2017-12-04 12:20:00
【问题描述】:

每当我运行我的程序时,屏幕都会打印“无法打开文件文件名”。我在我的讲义中遵循了指导方针和方法,真的不知道为什么它不会打开。任何形式的帮助将不胜感激。

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

#define READONLY "r"

int main (void)
{
  FILE *ipfile;
  char filename[FILENAME_MAX+1];
  int *unsorted_details;
  int elements;

  printf("Enter the name of the input file:\n");
  scanf("%s", filename);

  if((ipfile=fopen(filename, READONLY)) == NULL){
    fprintf(stderr, "Couldn't open %s. \n", filename);
    exit(EXIT_FAILURE);
  } 
  if (fscanf(ipfile, "%d", &elements) != 1){
    fprintf(stderr, "Couldn't read object details from %s\n", 
filename);
    exit(EXIT_FAILURE);
  }
  if ((unsorted_details=(int *)malloc(elements * sizeof(int))) == NULL){
    fprintf(stderr, "Failed to allocate memory.\n");
    exit (EXIT_FAILURE);
  }
  /* Reading elements from file into unsorted array*/
    int i;
  for (i=0; i<elements; i++){
    if(!fscanf(ipfile, "%d", &unsorted_details[i])){
        fprintf(stderr, "Error reading element %d of the list\n", i+1);
        exit (EXIT_FAILURE);
    }

   }
  fclose(ipfile);
  free(unsorted_details);
  return (EXIT_SUCCESS);
}

【问题讨论】:

  • 该文件可能在当前目录中不存在。
  • 对不起,我不知道你说的文件目录是什么意思,我该如何修改?
  • 将文件放在包含exe文件的同一目录中,并在给出输入的同时给出文件的扩展名。试一次..
  • 尝试输入完整的文件路径(绝对)。也尝试打印getcwd() 你可能不在你认为的目录中。
  • 您应该打印实际错误。阅读 fopen 文档(谷歌例如“man fopen”)。同时打印实际文件名和当前工作目录。

标签: c file-handling readonly


【解决方案1】:

大多数库函数都使用名为errno 的外部变量,当其中一个函数失败时设置该变量并指示失败的原因。

您可以通过调用perror 来获取错误消息的文本描述,它将错误消息打印到stderr,或者您可以调用strerror(errno),它返回一个char *,它指向错误消息您可以随后输入自己的错误消息。

如果调用 fopen 失败,请将您的错误消息更改为以下内容:

fprintf(stderr, "Couldn't open %s: %s \n", filename, strerror(errno));

您可以对其他错误消息进行类似的更改。执行此操作后,您将知道函数失败的原因并采取适当的措施。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-09-14
    • 2021-10-20
    • 1970-01-01
    • 1970-01-01
    • 2019-11-02
    • 1970-01-01
    • 1970-01-01
    • 2019-01-14
    相关资源
    最近更新 更多