写入 C 中的文件不起作用
Writing to a file in C not working
我有以下代码,输入字符后一直出现"Program has stopped working"错误。
我调试了一下,发现问题出在写入文件部分,但是我找不到问题。
谁能帮帮我? (我是 C 的新手)
#include <stdio.h>
int main()
{
char characters;
printf("Input your characters: ");
scanf("%s", &characters);
FILE *fp = fopen("File.txt", "w");
fprintf(fp, "%s", characters);
fclose(fp);
}
在您的代码中,characters
属于 char
类型,不适合存储 字符串 。您需要将 characters
作为数组。
本质上,由于 %s
,输入值(即使是单个 char
)被存储在所提供地址指向的内存中,但在此之后,尝试存储终止 null,导致越界访问。这会调用 undefined behavior.
引用 C11
,章节 §7.21.6.2,fscanf()
,(强调我的)
s
Matches a sequence of non-white-space characters.286)
If no l
length modifier is present, the corresponding argument shall be a
pointer to the initial element of a character array large enough to accept the
sequence and a terminating null character, which will be added automatically.
我有以下代码,输入字符后一直出现"Program has stopped working"错误。
我调试了一下,发现问题出在写入文件部分,但是我找不到问题。
谁能帮帮我? (我是 C 的新手)
#include <stdio.h>
int main()
{
char characters;
printf("Input your characters: ");
scanf("%s", &characters);
FILE *fp = fopen("File.txt", "w");
fprintf(fp, "%s", characters);
fclose(fp);
}
在您的代码中,characters
属于 char
类型,不适合存储 字符串 。您需要将 characters
作为数组。
本质上,由于 %s
,输入值(即使是单个 char
)被存储在所提供地址指向的内存中,但在此之后,尝试存储终止 null,导致越界访问。这会调用 undefined behavior.
引用 C11
,章节 §7.21.6.2,fscanf()
,(强调我的)
s
Matches a sequence of non-white-space characters.286)If no
l
length modifier is present, the corresponding argument shall be a pointer to the initial element of a character array large enough to accept the sequence and a terminating null character, which will be added automatically.