c - fopen 在 C 中返回无效参数

标签 c

我搜索了论坛,找不到这个问题的答案。这似乎很常见,但上述修复均不适用。

这是我打开文件的代码:

#include <stdio.h>
#include <string.h>

void main() {
    FILE *input;
    char path[200];

    printf("Enter the full file path and file name in the following format:"
        "\nC:\\Users\\Username\\etc......\\filename.extension\n");
    fgets(path, 200, stdin);
    printf("%s",path);
    input=fopen(path,"r");
    if (input==NULL) {
        perror("The following errors were encountered");
        return(-1);
    }
}

printf(%s,path) 正确显示我要打开的文件的路径和名称,但 fopen 总是返回无效参数。我也尝试过在 fopen 中使用指向路径的指针,但这总是会导致程序崩溃。

最佳答案

您正在使用 fgets 获取 path\nfgets 视为有效字符。您需要手动将其删除。

fgets(path, 200, stdin);
path[strlen(path) - 1] = '\0';

关于c - fopen 在 C 中返回无效参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26181211/

相关文章:

C - 这一行在这个结构中意味着什么?

c - 如何从 NUCLEO F091C 板获取 printf 输出

c - 如何从路径中提取文件名

c - 在 Visual Studio 2015 中强制执行 ANSI C 标准

c - 文件全局定义

c - 汉诺塔 - 用户正在移动磁盘 (c)

c - 在 C 中处理数组的未知方式

c - 如何在 C 中运行多个 execlp()?

c - 获取挂起线程的ThreadState

c - 在 EOF 处终止 scanf 并忽略字符串