Fopen不是打开文件,而是通过fget提供完整路径 [英] fopen won't open file, providing the full path via fgets
本文介绍了Fopen不是打开文件,而是通过fget提供完整路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要打开一个文件,提供完整路径。我使用函数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:UsersEdoDesktopsample.docx
C:\USERS\EDO\Desktop\sample.docx
C:/USERS/EDO/Desktop/sample.docx
C://USERS//EDO//Desktop//sample.docx
都不起作用
推荐答案
fgets
在字符串末尾保留换行符。您需要将其脱掉:
path[strlen (path) - 1] = ' ';
为此,您还需要#include <string.h>
。
这篇关于Fopen不是打开文件,而是通过fget提供完整路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文