我试图读取缓冲区中存储的值,但它显示我的地址?

时间:2016-04-15 10:24:30

标签: c file-handling fread

我想在不是地址的位置打印值。 当我使用断点运行程序时,它会增加值,但不会打印地址中包含的值。

compile()

这是输出:

size of file is :185153907
5bf894
5bf895
5bf896
5bf897
5bf898
5bf899
5bf89a
5bf89b
5bf89c
5bf89d
5bf89e
5bf89f
5bf8a0
5bf8a1
5bf8a2
5bf8a3
5bf8a4
5bf8a5
5bf8a6
5bf8a7
5bf8a8
5bf8a9
5bf8aa
5bf8ab
5bf8ac
5bf8ad
5bf8ae
5bf8af
5bf8b0
5bf8b1
5bf8b2
5bf8b3
5bf8b4
5bf8b5
5bf8b6
5bf8b7
5bf8b8
5bf8b9
5bf8ba
5bf8bb
5bf8bc
5bf8bd
5bf8be
5bf8bf
5bf8c0
5bf8c1
5bf8c2
5bf8c3
5bf8c4
5bf8c5
5bf8c6
5bf8c7
5bf8c8
5bf8c9
5bf8ca
5bf8cb
5bf8cc
5bf8cd
5bf8ce
5bf8cf
5bf8d0
5bf8d1
5bf8d2
5bf8d3
5bf8d4
5bf8d5
5bf8d6
5bf8d7
5bf8d8
5bf8d9
5bf8da
5bf8db
5bf8dc
5bf8dd
5bf8de
5bf8df
5bf8e0
5bf8e1
5bf8e2
5bf8e3
5bf8e4
5bf8e5
5bf8e6
5bf8e7
5bf8e8
5bf8e9
5bf8ea
5bf8eb
5bf8ec
5bf8ed
5bf8ee
5bf8ef
5bf8f0
5bf8f1
5bf8f2
5bf8f3
5bf8f4
5bf8f5
5bf8f6
5bf8f7

但我想要值..

1 个答案:

答案 0 :(得分:2)

首先,在fopen之后立即检查fp是否为NULL。第二次在fread之前寻找文件的开头。最后,最重要的是,检查fread的返回值,因为这是读入缓冲区的元素数量。它可能小于缓冲区。

   fp = fopen("D:\\Telenor_Short_01.vts","rb");//  binary mode
   if( fp == NULL ) //error checking
   {
      perror("Error while opening the file.\n");
      exit(EXIT_FAILURE);
   }

   fseek(fp,0,SEEK_END); //sets the file position of the stream to the given offset
   int size=ftell(fp); //returns the current file position of the given stream.
   printf("size of file is :%d\n",size);

   fseek(fp, 0, SEEK_SET);
   int nread = fread(p, 1, 100, fp);
   for (int i=0; i<nread; i++)
   {
       printf("%04x\n", *p);
       p++;
   }
   fclose(fp);

此外,在C中,您可以通过订阅或通过指针算法访问数组元素,这两个效果相同:

char arr[8];
arr[3] is same as *(arr + 3);
&arr[3] is same as arr + 3;

按块读取大文件:

fseek(fp, 0, SEEK_SET);
char buf[4096];
int nread;
int i;
while (1) {
    nread = fread(buf, 1, 4096, fp);
    for (i=0; i<nread; i++)
    {
        printf("%02x\n", buf[i]);
    }
    if (nread < 4096)
        break;
}
fclose(fp);