繁体   English   中英

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

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

当我尝试将数据写入二进制文件时出现问题。 这是代码:

#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;
}

当我运行程序时,它仅写入x.name字符串,而忽略其他2(数量和价格)。 我已经用谷歌搜索了,这似乎是将数据写入二进制文件的正确功能……但是它仍然对我不起作用。 我该怎么办? 提前致谢!

您的函数运行良好,问题是您写入了许多未使用的数据,没有使用正确的工具查看您的二进制文件。

您在名称中输入"test"该名称的大小为255个字符。 这将用完前五个字符(四个字母加上空终止符),而其余的250个字符未使用。 它们被写入文件,并且它们的内容成为"test"和其他数据之间的"test"垃圾填充”。

如果编写一个简单的程序以读取文件,则会发现数量和价格均正确设置为您编写的值:

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;
}

根据您的代码,您正在尝试写入x的地址。 但是,如果要编写完整的对象,则必须先序列化该对象。

暂无
暂无

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

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