问题描述
我正在尝试从具有数据的跟踪文件中读取数据,这是跟踪文件的前5行:
W 0x7fff6c5b7b80
R 0x7fff6c5b7c48
W 0x7fff6c5b7b88
R 0x7fff6c5b7c20
W 0x7fff6c5b7b90
。
。
。
这是我拥有的代码的一部分,在这里,我试图读取前5行并将其打印出来:
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
int main ()
{
// line buffer
FILE *fp;
char type;
unsigned int address;
fp = fopen("XSBENCH.t","r");
if(!fp)
{
printf("file not found\n");
}
for(int i = 0; i<5; ++i)
{
fscanf(fp,"%c %x",&type,&address);
printf("%c %x \n",type,address);
}
return 0;
}
这是我得到的确切输出:
W 6c5b7b80
6c5b7b80
R 6c5b7c48
6c5b7c48
W 6c5b7b88
解决方法
您环境中的unsigned int
似乎没有足够的宽度来存储数据。
数据将适合uint64_t
,因此使用它可以解决问题。
还将换行符读取到type
。将空白添加为scanf
格式意味着它将跳过空白字符(包括换行符),因此会有所帮助。
更多要点是,您不应该使用NULL
作为要读取的文件指针,而您却忘记了关闭文件。
尝试一下:
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <inttypes.h>
int main ()
{
// line buffer
FILE *fp;
char type;
uint64_t address;
fp = fopen("XSBENCH.t","r");
if(!fp)
{
printf("file not found\n");
return 1;
}
for(int i = 0; i<5; ++i)
{
fscanf(fp," %c %" SCNx64,&type,&address);
printf("%c %" PRIx64 " \n",type,address);
}
fclose(fp);
return 0;
}