如何在C中读取和打印二进制文件?
我正在努力从二进制文件中的阅读和打印。在下面,您可以看到带有主函数的代码。我能够实现写功能,但是在我想从中阅读并打印创建的二进制文件的读取部分中挣扎。
为每个答案感到高兴!
#include<stdio.h>
struct Person
{
char name[40];
int age;
};
void read()
{
puts("help");
}
void write()
{
struct Person ps[] = { {"Tom", 25}, {"Adam", 35} };
FILE *fo = fopen("1.bin", "wb");
fwrite(ps, sizeof(struct Person), 2, fo);
fwrite(ps, sizeof(ps), 1, fo);
fclose(fo);
}
int main(int argc, char *argv[])
{
switch(argv[1][0])
{
case 'w':
puts("w");
write();
break;
case 'r':
puts("r");
read();
break;
default:
puts("Error in command line");
}
return 0;
}
I'm struggling reading and printing from a binary file. Below you can see the code with main function. I was able to implement the write function, but struggling with the read part where I want to read from and print the binary file that was created.
Happy for every answer and help!
#include<stdio.h>
struct Person
{
char name[40];
int age;
};
void read()
{
puts("help");
}
void write()
{
struct Person ps[] = { {"Tom", 25}, {"Adam", 35} };
FILE *fo = fopen("1.bin", "wb");
fwrite(ps, sizeof(struct Person), 2, fo);
fwrite(ps, sizeof(ps), 1, fo);
fclose(fo);
}
int main(int argc, char *argv[])
{
switch(argv[1][0])
{
case 'w':
puts("w");
write();
break;
case 'r':
puts("r");
read();
break;
default:
puts("Error in command line");
}
return 0;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我将您的功能重命名为“ Person_”前缀不与标准功能冲突(如果您想在程序中使用这些功能)。实现
Person_Read()
,但传递指针并计数n
。另外,person_write()
可以编写初始记录计数。您还可以实现一个函数,该函数计算文件中的记录数,也可以坚持person_read()
在堆上分配合适的数组并返回指针。您还可以一次阅读唱片直到EOF,但这更是一种设计更改。如果您没有指定任何参数,则修复了segfault。检查fopen()
,fread()
和fwrite()的错误。考虑使用年龄的无符号(char)而不是
int
。I renamed your functions with a "person_" prefix as not to conflict with standard functions (if you ever want to use those in your program). Implemented
person_read()
but passing a pointer and countn
. Alternatively,person_write()
could write an initial record count. You could also implement a function that counts number of records in your file, or insist onperson_read()
allocating a suitable array on the heap and return a pointer. You could also read a record at a time till EOF but that is more a design change. Fixed the segfault if you were not specifying any arguments. Check for errors offopen()
,fread()
andfwrite()
. Consider using an unsigned (char) for age instead of anint
.