gpt4 book ai didi

c - C语言读取文件的困境

转载 作者:行者123 更新时间:2023-11-30 20:55:59 25 4
gpt4 key购买 nike

这是我的第一个问题,希望大家能帮忙。在类里面,我的任务是编写一个 C 代码,从一个文件中读取一组字符串,并将它们以及字符串中每个字符的 ASCII 代码以及 ASCII 代码值的总和打印到另一个文件中。下面的代码已编译,但未执行。代码是正确的,但我做错了什么,或者代码根本就是错误的。非常感谢。

注意:第一个文件从名为 list 的文本文件中读取,代码打印到名为 list2 的文本文档中。

#include <stdio.h>

int main(void)
{
FILE *file1, *file2;

file1 = fopen("list.txt", "r");

if (file1==NULL)
{
puts(" File not exisiting\n");
}

file2 = fopen("list2.txt", "w");

if (file2==NULL)
{
puts(" File could not open \n");
}

char a[5];
fscanf(file1, "%s", a);
int b,c;

while (a[5]!=EOF)
{
for (int i=0;i<5;i++)
{
fprintf(file2, "%c", a[i]);
b=a[i];
fprintf(file2, "%d", b);

c+=b;
}
}

fprintf(file2, "%d", c);
return 0;



}

最佳答案

第 1 点。定义如下

char a[5];

使用

while (a[5]!=EOF)

调用undefined behaviour 。你面临着差一的错误。请记住,c 中的数组索引从 0 开始。有效访问最多可达 a[4]

<小时/>

第 2 点 fscanf(file1, "%s", a); 不安全。它可能会导致缓冲区溢出。至少,你需要写

 if ( fscanf(file1, "%4s", a) != 1)
{
//scanning not successful, take necessary measures
}
//otherwise, continue nomal execution.
<小时/>

第 3 点。while 循环的逻辑不正确。那里没有 break 条件。

<小时/>

第4点 c+=b;,这里c未初始化。 先读后写场景。再次,undefined behaviour 。请记住,auto 局部变量不会自动初始化为 0 或某个值。您必须显式初始化。

<小时/>

第5点如果满足if (file1==NULL)条件,则不继续正常执行。仅打印消息是不够的。您应该停止该程序并避免使用 file1file1 等。

<小时/>

第 5 点的来源:user4402433

关于c - C语言读取文件的困境,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29165148/

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