简体   繁体   English

如何在C中将数据写入二进制文件

[英]How to write data to a binary file in C

I've got a problem when i try to write data to a binary file. 当我尝试将数据写入二进制文件时出现问题。 This is the code: 这是代码:

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

typedef struct
{
char name[255];
int quantity;
float price;
} product;

int main()
{
product x;
FILE *f;
strcpy(x.name,"test");
x.quantity=10;
x.price=20.0;
f=fopen("test.txt","wb");
fwrite(&x,sizeof(x),1,f);
fclose(f);
return 0;
}

When I run the program,it only writes the x.name string,ignoring the other 2(quantity and price). 当我运行程序时,它仅写入x.name字符串,而忽略其他2(数量和价格)。 I've googled it and this seems to be the correct function to write data to a binary file...but it still doesn't work for me. 我已经用谷歌搜索了,这似乎是将数据写入二进制文件的正确功能……但是它仍然对我不起作用。 What should I do? 我该怎么办? Thanks in advance! 提前致谢!

Your function works fine, the problem is that you write a lot of unused data, are not using the right tool to view your binary file. 您的函数运行良好,问题是您写入了许多未使用的数据,没有使用正确的工具查看您的二进制文件。

You put "test" into the name, which has a size of 255 characters. 您在名称中输入"test"该名称的大小为255个字符。 This uses up the first five (four letters plus null terminator) while the remaining 250 characters are unused. 这将用完前五个字符(四个字母加上空终止符),而其余的250个字符未使用。 They are written to the file, and their content become "junk filling" between "test" and the other data. 它们被写入文件,并且它们的内容成为"test"和其他数据之间的"test"垃圾填充”。

If you write a simple program to read your file back, you would discover that both the quantity and the price are set correctly to the values that you wrote: 如果编写一个简单的程序以读取文件,则会发现数量和价格均正确设置为您编写的值:

int main()
{
    product x;
    FILE *f;
    f=fopen("test.txt","rb");
    fread(&x,sizeof(x),1,f);
    fclose(f);
    printf("'%s' - %d %f\n", x.name, x.quantity, x.price);
    return 0;
}

According to your code you are trying to write address of x. 根据您的代码,您正在尝试写入x的地址。 But if you want to write full object then you have to serialize the object first. 但是,如果要编写完整的对象,则必须先序列化该对象。

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

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