gpt4 book ai didi

c - 当程序从文件中读取字符时,它也会读取一些垃圾

转载 作者:行者123 更新时间:2023-11-30 20:12:51 24 4
gpt4 key购买 nike

该程序从文件 RDLRDLLLL 读取到缓冲区,然后传输到 char 数组,最终将每个字符转换为伪代码。问题是:它还读取了一些奇怪的字符,所以我的问题是:问题出在哪里?

#define n 100

void main() {
int i;
char tablou_init[n];

FILE *fp;
long lSize;
char *buffer;

fp = fopen("date.in", "r");
if (!fp) perror("date.in"), exit(1);

fseek(fp, 0L, SEEK_END);
lSize = ftell(fp);
rewind(fp);

/* allocate memory for entire content */
buffer = calloc(1, lSize + 1);
if (!buffer) fclose(fp), fputs("memory alloc fails", stderr), exit(1);

/* copy the file into the buffer */
if (1 != fread(buffer, lSize, 1, fp)) fclose(fp), free(buffer), fputs(
"entire read fails", stderr), exit(1);

strcpy(tablou_init, buffer);

for (i = 0; i < n; i++) {
if (tablou_init[i] == 'R') printf("<program>\n");
else if (tablou_init[i] == 'D') printf("<secventa de instructiuni>\n");
else if (tablou_init[i] == 'L') printf("<consecutivitate de descrieri>\n");
else if (tablou_init[i] == 'T') printf("<tip>\n");
else if (tablou_init[i] == 'I') printf("<lista de identificatori>\n");
else if (tablou_init[i] == 'S') printf("<consecutivitate de instructiuni>\n");
else if (tablou_init[i] == 'A') printf("<instructiunea de Atribuire>\n");
else if (tablou_init[i] == 'F') printf("<instructiunea IF>\n");
else if (tablou_init[i] == 'H') printf("<instructiune>\n");
else if (tablou_init[i] == 'W') printf("<instructiunea WHILE>\n");
else if (tablou_init[i] == 'i') printf("<identificator>\n");
else if (tablou_init[i] == 'e') printf("<expresie>\n");
}

fclose(fp);
free(buffer);
for (i = 0; i < n; i++) {
printf("%c", tablou_init[i]);
}

}

program run

最佳答案

问题很简单:

您将文件内容读入buffer,然后将其复制到tablou_init。不检查潜在的溢出是有风险的,但我们假设文件实际上只包含几个字节:这些字节和尾随的 '\0'strcpy 复制,但 tablou_init 的其余部分未初始化。

因此,从 0n 循环整个 tablou_init 可能会产生随机输出,作为超出 '\0' 的字节 是不确定的,可能是有效但意外的指令。

修复很简单,将两个 for 循环更改为:

for (i = 0; i < lSize; i++)

从技术上讲,不需要 tablou_init 数组,循环遍历 buffer 的内容更简单、更安全。

使用 fgets() 从输入文件中读取行比当前方法更可靠:您无法使用 ftell() 可靠地计算文件大小。 C11 7.21.9.4 说:对于文本流,其文件位置指示符包含未指定的信息,fseek 函数可使用这些信息将流的文件位置指示符返回到 ftell 调用时的位置;。您确实以文本模式打开流。这可能无法解释您的问题,但此方法不可移植。

关于c - 当程序从文件中读取字符时,它也会读取一些垃圾,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34009166/

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