【问题标题】:fopen won't open file, providing the full path via fgetsfopen 不会打开文件,通过 fgets 提供完整路径
【发布时间】:2021-07-07 02:05:08
【问题描述】:

我需要打开一个文件,提供完整路径。我使用函数 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 文档:如果读取换行符,则将其存储到缓冲区中。您需要 get rid of the newline character at the end of the line 才能获得有效的文件名。
  • 如果您想了解为什么这不起作用(尽管@lurker 可能是正确的),请使用 sysinternals procmon,它会显示您的程序执行的所有文件操作以及它们失败的原因
  • 顺便说一句,您可能希望考虑将 printf("Error"); 替换为 perror(path)

标签: c fopen


【解决方案1】:

fgets 在字符串末尾留下换行符。你需要把它去掉:

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

您也需要#include &lt;string.h&gt;

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-02-21
      • 2017-02-04
      • 1970-01-01
      • 2010-10-24
      • 1970-01-01
      • 2015-05-29
      • 1970-01-01
      相关资源
      最近更新 更多