如何将int数组和char数组都写入文件 [英] How can I write both an array of int and array of char to a file

查看:545
本文介绍了如何将int数组和char数组都写入文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在二进制文件中写入和读取一组int。这两个函数或多或少看起来像这样。

Im trying to write and read an array of ints in a binary file. The two functions look like this, more or less.

int numbers[6]={0, 2, 3, 3, 0, 1};
FILE *file;
if(file=fopen(filename, "wb")==NULL)
{
    printf("Something went wrong reading %s\n", filename);
    return 0;
}
else
{
    int i;
    for(i=0; i<6; i++)
        fprintf(file, "%d", numbers[i]);
}
fclose(file);



loadfunction



loadfunction

FILE *saved_data;
int errors=0;
if((saved_data=fopen(filename, "rb"))==NULL)
    errors++;
else
{
    fread(first, sizeof(int), 1, saved_data);
    fread(second, sizeof(int), 1, saved_data);
    fread(third, sizeof(int), 1, saved_data);
    fread(fourth, sizeof(int), 1, saved_data);
    fread(fifth, sizeof(int), 1, saved_data);
    fread(sixt, sizeof(int), 1, saved_data);
}
fclose(saved_data);

现在,当我调试程序时,调试器告诉我第一个元素是以下

Now when I debug the program the debugger tells me that the first element is the following

(gdb) print first
$1 = (int *) 0x7fff5fbff968
(gdb) print *first
$2 = 858993200

我无法理解这一点。用编辑器打开时的文件说 023301

I can't understand this. The file when opening with editor says 023301

推荐答案

补充功能 fread fwrite ,而不是 fprintf 。您正在使用 fprintf 将整数作为文本放入文件中,而不是二进制文件。

The complementary function of fread is fwrite, not fprintf. What you're doing with fprintf is putting the integers into the file as text, not as binary.

,确保传递指向 fread 的指针,而不是整数。你没有显示第一个第二个的声明,依此类推,但如果你已经声明了类似的声明

Also, make sure you pass a pointer to fread, not an integer. You don't show the declarations of first, second, and so on, but if you've declared something like

int first, second, third, fourth, fifth, sixt;

然后你需要使用像

fread(&first, sizeof(int), 1, saved_data);

而不是

fread(first, sizeof(int), 1, saved_data);

由于你的整数已经在数组中,你可以一次性编写数组

Since your integers are already in an array, you can just write the array in one go with

fwrite(numbers, sizeof(int), 6, file);

并完全避免 循环。

这篇关于如何将int数组和char数组都写入文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆