我需要打开一个文件,提供完整的路径。我使用函数 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:\用户\Edo\桌面\样本.docx
C:\\用户\\Edo\\桌面\\样本.docx
C:/Users/Edo/Desktop/sample.docx
C://Users//Edo//Desktop//sample.docx
他们都不起作用
fgets
将换行符保留在字符串的末尾。 您需要将其剥离:
path[strlen (path) - 1] = ' ';
您也需要为此#include <string.h>
。
谢谢@lurker,他告诉我有什么问题,我以这种方式修复了代码
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main () {
FILE *file;
char path[300];
printf("Insert string: ");
fgets(path, 300, stdin);
strtok(path, "n");
file = fopen(path,"rb");
if (file == NULL) {
printf("Error");
exit(0);
}
return 0;
}