gpt4 book ai didi

将内容写入文件的 C 代码不起作用

转载 作者:行者123 更新时间:2023-11-30 21:05:49 24 4
gpt4 key购买 nike

这是我编写的用于向文件写入内容的 C 代码。但是当我编译它时,进程终止而没有获得内容的输入。错误是什么?

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

void main()
{
FILE *fp;
char name[20];
char content[100];

printf("Enter file name:\n");
scanf("%s", name);

printf("Enter the content:\n");
gets(content);

fp = fopen(name, "w");

fprintf(fp, "%s", content);
fclose(fp);
}

最佳答案

它直接越过了gets行。为什么?因为the scanf family has lots and lots of problems 。避开它们。

Specifically it tends to leave input on the buffer 。在本例中,scanf("%s", name);读入所有文本并在stdin上留下换行符。然后 gets 尽职尽责地读取该换行符...并将其扔掉,因为这就是 gets 的行为方式。如果我们在 gets 之前打印名称和内容,我们就可以看到这一点。

printf("name: '%s'\n", name);
printf("content: '%s'\n", content);

name: 'foo'
content: ''

然后你的程序就会尽职尽责地不向文件写入任何内容。

相反,使用 fgets 读取整行,并使用 sscanf 解析它们。这避免了将输入留在缓冲区上的危险。

printf("Enter file name:\n");
fgets(name, sizeof(name), stdin);

printf("Enter the content:\n");
fgets(content, sizeof(content), stdin);

fgets 不会删除换行符,因此您必须自己执行此操作。 There's a variety of ways to do it .

void trim( char *string, char to_trim ) {
size_t len = strlen(string);
if( len == 0 ) {
return;
}
size_t last_idx = len -1;
if( string[last_idx] == to_trim ) {
string[last_idx] = '\0';
}
}

我更喜欢这种方法,因为它只删除换行符(如果它是最后一个字符)。

最后,始终检查您的文件操作。您没有检查 fopen 是否成功。如果由于某种原因失败,您将收到另一个神秘错误。就我而言,我用于测试的名称已经作为目录存在。

#include <string.h>  // for strerror
#include <errno.h> // for errno

fp = fopen(name, "w");
if( fp == NULL ) {
fprintf(stderr, "Could not open '%s' for writing: %s.\n", name, strerror(errno));
return 1;
}

关于将内容写入文件的 C 代码不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52468629/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com