gpt4 book ai didi

c - 如何将结构体成员写入文件?

转载 作者:行者123 更新时间:2023-11-30 15:31:52 26 4
gpt4 key购买 nike

#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <stdlib.h>

typedef struct {
char name[124];
int age;
int class;
} student;

main( ) {
student s1;
int fd = -1;
int fh = creat( "student.db", O_CREAT | S_IRUSR | S_IWUSR );
fd = open( "student.db", O_RDWR | O_APPEND );
if ( fd<0 ) {
perror( "failed to create student file:" );
return;
}
s1.age = 15;
s1.class = 9;
strcpy( s1.name, "John" );
int ret = write( fd, &s1, sizeof( student ) );
printf( "ret of write: %d \n", ret );
system( "gvim student.db" );
}

我正在尝试将记录写入文件。由于结构体包含整数元素,因此仅名称写入成功,而 int 元素显示为垃圾。有人可以看一下代码吗?任何帮助将不胜感激。

最佳答案

使用像 od -x 这样的命令,您可以获得对调试有用的文件内容的十六进制转储。如果您重新排序结构成员,那么您会更容易,因此整数位于第一位。

一个示例,显示一个包含从 0.. 开始的 64 位斐波那契数列计数的文件:

ladm@ash:~/src/fib/fibs_tab> od -x < fib_uint64| head
0000000 005e 0000 0000 0000 0000 0000 0000 0000
0000020 0001 0000 0000 0000 0001 0000 0000 0000
0000040 0002 0000 0000 0000 0003 0000 0000 0000
0000060 0005 0000 0000 0000 0008 0000 0000 0000
0000100 000d 0000 0000 0000 0015 0000 0000 0000
0000120 0022 0000 0000 0000 0037 0000 0000 0000
0000140 0059 0000 0000 0000 0090 0000 0000 0000
0000160 00e9 0000 0000 0000 0179 0000 0000 0000
0000200 0262 0000 0000 0000 03db 0000 0000 0000
0000220 063d 0000 0000 0000 0a18 0000 0000 0000

第一个整数是计数 0x5e (93),后跟 3 个空的高有效字节,然后序列开始。 0,1,1,2,3,5 等等。

关于c - 如何将结构体成员写入文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24516669/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com