我需要打开一个文件,提供完整路径。我使用函数 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
将换行符留在字符串的末尾。你需要把它去掉:
path[strlen (path) - 1] = '\0';
您需要 #include <string.h>
也是为了这个。
关于c - fopen 不会打开文件,通过 fgets 提供完整路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48591067/