我试图逐行读取文本文件并打印前 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/