c - fopen 不会打开文件,通过 fgets 提供完整路径

标签 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:\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/

相关文章:

mysql - 将 sprintf 与 mysql_query 结合使用

c - 在 C 中读取包含 long 数组的文件

c - 如何从 C 语言的文件中读取行?

c++ - 简单的跨平台剪贴板库?

c - 递归 - 链表中倒数第 n 个元素

c - Windows : trouble with command line arguments 上的进程和线程 C 编程

c - 如何在 C 中使用 strstr 循环字符串来查找子字符串

c - 确定打开的文件是否已在 C 中被修改

c - fopen 是否创建文件描述符?