【发布时间】: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