gpt4 book ai didi

无法从c文件中读取字符串

转载 作者:太空宇宙 更新时间:2023-11-04 06:35:55 25 4
gpt4 key购买 nike

我试图逐行读取文本文件并打印前 17 个字符。

FILE *devices;
devices = NULL;
devices = fopen("devices.txt", "r");

char deviceaddr[17];
char addr[17];

char line[1024];

while (fgets(line,1024,devices) != NULL)
{
fscanf(devices,"%s", deviceaddr);

printf("%s\n", deviceaddr);
}

fclose(devices);

第一行的输出应该是 00:07:80:4C:0E:EE 但它给出了 6

最佳答案

while 循环正在读取一行文本,然后 fscanf 将读取下一组文本(并且可能会偶然溢出该缓冲区)。似乎您应该只是从缓冲区 line 打印循环内的所需数据。

例如,假设有三行文本。

00:07:80:4C:0E:EE    --> ends up line buffer line
second --> ends up in deviceaddr
third line --> ends up in line (unless the fscanf did not consume newline)

关于无法从c文件中读取字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15070121/

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