fgets() 不是 working.in C?

fgets() not working.in C?

编辑:删除了除主要问题以外的所有内容。

我这里的程序应该在指定的目录下创建一个文件,并向其中写入指定的文本。正确的文件路径和内容应如下所示:

Path: D:\test.txt
Content: The printing succeeded.

出于某种原因,我的代码无法识别 "path" 变量。我不知道我在这里做错了什么。 "text" 变量工作正常。

#include<stdio.h>
int main()
{

//Declaring variables
char path[999];
char text[999];
FILE *fp;

//prompting for path variable
printf("Specify a file path.\n");
fgets(path,999,stdin);
printf(path);

//prompting for the text variable.
printf("What do you want to write?");
fgets(text,999,stdin);
printf(text);

//opening and printing to file.
//fp = fopen("D:\test.txt", "w");
fp = fopen(path, "w");
fprintf(fp, text);
fclose(fp);

//test print to see that the program completed correctly.
printf("\nThe printing has been done.");
return 0;
}

我不明白的是 fp = fopen("D:\test.txt", "w"); 有效,但 fp = fopen(path, "w"); 无效。我试过放入这些不同的路径。:

D:\test.txt
D:\test.txt
D\test.txt
D\test.txt

当你打开变量 path 时它不会打开文件,因为 fgets() 读取 newline 并将其放在字符串的末尾(如果有足够的 space 在缓冲区中)。为了使其工作,您必须从字符串中手动删除 newline

在打开文件之前尝试此操作。

  if(isspace(path[strlen(path)-1]))
             path[strlen(path)-1]='[=10=]';

您可能还需要包括 <ctype.h>