在 C 中作为用户输入的文件路径

File path as user input in C

我找不到我的问题的具体答案。我的水平真的很低,刚开始并有一个class,我在其中学会了从 CodeBlocks 创建文件。把代码带回家,但它不会工作,因为它不在同一台计算机上。因此,我们的想法是制作一些允许用户为新形成的 .txt 文件选择路径的东西。当我手动插入 "c:\example.txt" 或类似的东西而不是 s 时,代码会创建一个文件 "example.txt" 但是当我将它作为输入发送时它根本不会。为什么?

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

int main()
{
    FILE *a=NULL;
    char s[50];
    puts("Enter the path of the file: ");
    fgets(s,50,stdin);
    a=fopen(s,"w");
    if(a==NULL)
        exit(1);
    else
        printf("Successful input");
}

So the entire problem was the fgets function which adds the \nat the end? Is there any other idea to make this work?

你可以替换

    fgets(s,50,stdin);

    scanf("%49[^\n]%*c", s);

- 这会将不包括 \n 的输入读入 s,只要它的大小允许,并消耗 \n,这样它就不会妨碍以后可能的输入。