【发布时间】:2015-02-19 01:45:09
【问题描述】:
我很确定这是打开文件的方式:
int readFile(char *filename){
char *source = NULL;
int fileSize;
char nameFile[strlen(filename)];
strcpy(nameFile,filename);
puts(nameFile);//Check if the string is correct
FILE *fp;
if ((fp =fopen(nameFile, "r")) != NULL) {
/* Go to the end of the file. */
if (fseek(fp, 0L, SEEK_END) == 0) {
/* Get the size of the file. */
long bufsize = ftell(fp);
if (bufsize == -1) { /* Error */ }
/* Allocate our buffer to that size. */
source = malloc(sizeof(char) * (bufsize + 1));
fileSize = (sizeof(char) * (bufsize + 1));
/* Go back to the start of the file. */
if (fseek(fp, 0L, SEEK_SET) != 0) { /* Error */ }
/* Read the entire file into memory. */
size_t newLen = fread(source, sizeof(char), bufsize, fp);
if (newLen == 0) {
fputs("Error reading file", stderr);
} else {
source[++newLen] = '\0'; /* Just to be safe. */
}
}
fclose(fp);
} else{
printf("File Doesnt Exist. :( \n");
return 0;
}
所以,我在我的工作目录中。当我编译时,可执行文件是在文件所在的位置创建的。我做了一个 puts 来比较文件的名称。文件名(与终端显示的相同); 我将“r”切换为“r+”,但我仍然发现我的文件不存在。 另外,我做了 fopen("actualFileName.txt") 并且它确实有效......所以......有什么想法吗??
这就是我调用 readFile 的方式:
fgets(userInput,sizeof(userInput),stdin);
readFile(userInput);
【问题讨论】:
-
你试过
char nameFile[strlen(filename)+1];和nameFile[strlen(filename)]='\0'吗?闻起来像离我更近的失踪者! -
为什么要复制文件名
-
@pm100 你说得对,首先不需要复制文件名。他可能正在尝试调试 fopen 失败的原因
-
以下建议使用 perror 会有所帮助