繁体   English   中英

保存后从C中的二进制文件读取

[英]Reading from binary file in C after saving

我正在尝试读取我创建的二进制文件。 打印无效,并且打印编号设置为(354),甚至在文件中也没有。 我很乐意为我的问题提供帮助。

#include <stdio.h>
#include <stdlib.h>

int test();

int main(void) {

FILE *f;

    f = fopen("nums.bin", "wb");

    srand(40); 

    for(int i = 0; i<20; i++) 
        fprintf(f, "%d ", rand()%1000); 
    printf("Numbers saved to file.\n");
    fclose(f);

    test();
    return 0;
}

int test() {

FILE *f;
int i=0;
    printf("The numbers in the file are...\n");
    f = fopen("nums.bin", "rb");

    fread(&i, sizeof(i), 2, f);
    printf("%d", rand()%1000);
return 0;
}

其他所有内容均按预期工作(文件中的数字与我希望的数字相同,等等)。 从文件中打印出来有点问题。 谢谢

您将数字写为文本:

    fprintf(f, "%d ", rand()%1000); 

但您将数字读为二进制

fread(&i, sizeof(i), 1, f);

这是不兼容的。

如果使用该fprintf进行编写,则必须使用fscanf或等效的格式为“%d”的文件进行读取,例如在编写时。

否则就读fread(&i, sizeof(i), 1, f); 你必须这样写:

int n = rand()%1000;

fwrite(&n, sizeof(n), 1, f);

除此之外,您的代码中有些奇怪:

printf("The numbers in the file are...\n");
...
fread(&i, sizeof(i), 2, f);
printf("%d", rand()%1000);

因此,您读取了一个数字(无论采用哪种方式),但没有打印,而是打印了一个随机值,为什么不打印i

printf("The numbers in the file are...\\n");之后printf("The numbers in the file are...\\n"); 它似乎逻辑到一个类似从文件中读取值,并将其打印在stdout


用二进制写/读的建议:

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

void test();

int main(void)
{
  FILE *f = fopen("nums.bin", "wb");

  if (f == 0) {
    puts("cannot open file to write in");
    return -1;
  }

  srand(time(NULL)); /* practical way to have different values each time the program runs */

  for (int i = 0; i<20; i++){
    int n =  rand()%1000; 

    printf("%d ", n); /* to check the read later */
    fwrite(&n, sizeof(n), 1, f);
  }
  printf(" are saved to file.\n");
  fclose(f);

  test();
  return 0;
}

void test() {
  FILE *f = fopen("nums.bin", "rb");

  if (f == 0) {
    puts("cannot open file to read in");
    return;
  }

  printf("The numbers in the file are :\n");

  for (int i = 0; i<20; i++){
    int n;

    fread(&n, sizeof(n), 1, f);
    printf("%d ", n);
  }

  putchar('\n');
  fclose(f);
}

示例(值每次都会更改):

pi@raspberrypi:/tmp $ gcc -pedantic -Wall r.c
pi@raspberrypi:/tmp $ ./a.out
208 177 118 678 9 692 14 800 306 629 135 84 831 737 514 328 133 969 702 382  are saved to file.
The numbers in the file are :
208 177 118 678 9 692 14 800 306 629 135 84 831 737 514 328 133 969 702 382 

您的随机化初始化srand(40)将不会影响您的随机数的质量。 您通常应该使用srand(time(null))东西来获得更“随机”的东西。

test结束时,您的输出将打印一个随机数,而不是您之前读取的整数。 另外,您正在读取fread(&i, sizeof(i), 2, f);行中的两个整数fread(&i, sizeof(i), 2, f); 这将破坏您的堆栈。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM