fopen不会打开文件,通过fgets

时间:2018-02-02 21:24:35

标签: c fopen

我需要打开一个文件,提供完整路径。我使用函数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:\用户\江户时代\桌面\ sample.docx

C:\\用户\\江户时代\\桌面\\ sample.docx

C:/Users/Edo/Desktop/sample.docx

C://Users//Edo//Desktop//sample.docx

它们都不起作用

2 个答案:

答案 0 :(得分:3)

fgets将换行符留在字符串的末尾。你需要剥掉它:

path[strlen (path) - 1] = '\0';

您也需要#include <string.h>

答案 1 :(得分:0)

谢谢@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;
}