如何使用write()函数将结构写入文件?

mor*_*rty 1 c c++ posix file-descriptor

我想使用write()函数将struct对象写入文件.它必须是那个功能.

我在终端的输入是:./ main.c output.dat John Doe 45

当我运行程序并打开output.dat时,有一堆字母没有意义.请帮我.

我在output.dat文件中想要的输出是:John Doe 45

我的代码:

struct Person{
  char* name;
  char* lastName;
  char* age;
};

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

    struct Person human;
    /* get the argument values and store them into char*         */
    char* fileName = argv[1];
    char* name = argv[2];
    char* lastName = argv[3];
    char* age = argv[4];

    /* set the values of human object */
    human.name = name;
    human.lastName = lastName;
    human.age = age;

    /* open the file */
    int file = 0;
    file = open(fileName, O_RDWR); /* I want to have read&write set! */
    write(file, &human, sizeof(human));
    close(file);


    return 0;
}
Run Code Online (Sandbox Code Playgroud)

Sha*_*ger 5

编写结构时,只能在struct自身中编写值.在您的情况下,这些值是指向内存中其他位置的指针,而不是字符串数据.因此,您最终会编写三个指针的内存地址(在大多数系统上为12或24个字节)并不是那么有用(因为它们适用于当前正在运行的程序的内存空间,这在内存空间上是不一样的下一次运行).

您将需要设计一个更有用的序列化格式,实际写出字符串的内容,而不是它们的地址.选项包括简单换行或NUL分隔文本,二进制长度前缀文本,或第三方库以使其正确,CSV,JSON或XML(如果您有野心,某种数据库).

例如,使用二进制长度前缀文本,您可能会执行以下操作:

uint32_t len;

len = strlen(name);
write(file, &len, sizeof(len));
write(file, human.name, len);
len = strlen(lastName);
write(file, &len, sizeof(len));
write(file, human.lastName, len);
... repeat for age ...
Run Code Online (Sandbox Code Playgroud)

它允许您通过读取每个字符串长度(固定大小)来读取它,然后使用它来确定必须读取多少字节才能获得字符串.