将带有char*字符串的C结构保存到文件中

the*_*ole 7 c file-io struct file

我正在尝试将带有char*字符串的结构保存到文件中.

struct d_object {
    int flags;
    int time;
    int offset;
    char *filename;
};
Run Code Online (Sandbox Code Playgroud)

问题是,当这样做时,我显然只会保存该指针的地址而不是字符串.所以我所做的只是使用一个字符数组,但我被迫设置字符串的最大大小.这工作正常,但我想知道是否有任何存储结构与文件中的char*(我在某些时候malloc),然后检索它.我可以保存字符串和结构分开,然后检索它们,但它是相当混乱.如果我可以将整个结构(上面的结构)加载并保存到文件中,那将是更好的选择.谢谢!

char数组的代码如下:

#include <stdio.h>
#include <string.h>
#include <fcntl.h>

struct d_object {
    int flags;
    int time;
    int offset;
    char filename[255];
};

int main(int argc, char **argv) {

    struct d_object fcb;

    fcb.flags=5;
    fcb.time=100000;
    fcb.offset=220;
    strncpy(fcb.filename,"myfile",255);


    int fd=open("testfile",O_RDWR);
    write(fd,&fcb,sizeof(fcb));
    close(fd);


    int fd2 = open("testfile",O_RDONLY);
    struct d_object new_fcb; 
    read(fd2,&new_fcb,sizeof(new_fcb));

    printf("read from file testfile: %s\n",new_fcb.filename);

    return 0;

}
Run Code Online (Sandbox Code Playgroud)

PS:我没有使用STREAM函数,因为这实际上是指在没有它们的嵌入式操作系统上运行.我刚刚调整了*BSD/Linux的代码,所以在提问时更有意义.

Bal*_*arq 7

我知道可移植性不是问题,因为您正在为嵌入式系统工作.在其他情况下,您应该使用类似XML的东西.

您可以将代码转换回:

struct d_object {
    int flags;
    int time;
    int offset;
    char * filename;
};
Run Code Online (Sandbox Code Playgroud)

然后单独保存每个数据:

write( fd, &record.flags, sizeof( int ) );
write( fd, &record.time, sizeof( int ) );
write( fd, &record.offset, sizeof( int ) );
int filename_length = strlen( filename );
write( fd, &filename_length, sizeof( int ) );
write( fd, record.filename, filename_length );
Run Code Online (Sandbox Code Playgroud)

对于阅读,你必须分开阅读每个项目,然后是文件名:

int filename_length;

read( fd, &emptyRecord.flags, sizeof( int ) );
read( fd, &emptyRecord.time, sizeof( int ) );
read( fd, &emptyRecord.offset, sizeof( int ) );

read( filename_length, sizeof( int ), 1, file );
emptyRecord.filename = (char *) malloc( sizeof( char ) * ( filename_length  +1) );
read( fd, emptyRecord.filename, filename_length );
*( emptyRecord.filename + filename_length ) = 0;
Run Code Online (Sandbox Code Playgroud)