【发布时间】:2021-07-07 02:05:08
【问题描述】:
我需要打开一个文件,提供完整路径。我使用函数 fopen 打开文件,这有效
#include <stdio.h>
#include <stdlib.h>
int main () {
FILE *file;
file = fopen("C:\\Users\\Edo\\Desktop\\sample.docx","rb");
if (file == NULL) {
printf("Error");
exit(0);
}
return 0;
}
但我真正需要的是让用户选择他想要的文件,但是这段代码不起作用。
#include <stdio.h>
#include <stdlib.h>
int main () {
FILE *file;
char path[300];
printf("Insert string: ");
fgets(path, 300, stdin);
file = fopen(path,"rb");
if (file == NULL) {
printf("Error");
exit(0);
}
return 0;
}
我试过作为输入:
C:\Users\Edo\Desktop\sample.docx
C:\\Users\\Edo\\Desktop\\sample.docx
C:/Users/Edo/Desktop/sample.docx
C://Users//Edo//Desktop//sample.docx
它们都不起作用
【问题讨论】:
-
我假设当用户输入完整路径时,它会以换行符终止。根据
fgets文档:如果读取换行符,则将其存储到缓冲区中。您需要 get rid of the newline character at the end of the line 才能获得有效的文件名。 -
如果您想了解为什么这不起作用(尽管@lurker 可能是正确的),请使用 sysinternals procmon,它会显示您的程序执行的所有文件操作以及它们失败的原因
-
顺便说一句,您可能希望考虑将
printf("Error");替换为perror(path)行