注册 登录
编程论坛 C++教室

关于结构写入文件

zabbey 发布于 2007-12-22 20:45, 701 次点击
我定义了一个结构,里面有指针,像这个样子
typedef struct caption {
    int length;
    char *name;
};
现在要把这个结构写入文件,但是写到文件中直接是name指针写到了文件,我想在把结构写入到文件的时候把name指向的内容写入到文件,如何才能做到呢,不想分开写入文件(先把length写入,然后取name指向的内容再写入)。

[[italic] 本帖最后由 zabbey 于 2007-12-22 20:47 编辑 [/italic]]
1 回复
#2
HJin2007-12-23 04:22
complete sample code is written for you as below:
程序代码:
#include <stdio.h>
#include <string.h>


/**
you are storing a char-pointer in the struct,
so memory for name should be allocated outside
the struct.
*/
typedef struct caption
{
    int length;
    char *name;
};




int main(int argc, char** argv)
{
    struct caption c[3];
    char names[3][128] =
    {
        "John Doe",
        "Jane M. Lequi",
        "Peter T. Campbell"
    };
    FILE* fp;
    const char* fname = "a.txt";
    int i;

    c[0].length = 1;
    c[0].name = names[0];
    c[1].length = 2;
    c[1].name = names[1];
    c[2].length = 3;
    c[2].name = names[2];

    fp = fopen(fname, "w");
    if(!fp)
    {
        // do something
    }

    for(i=0; i<3; ++i)
    {
        fprintf(fp, "%d %s\n", c[i].length, c[i].name);
    }

    fclose(fp);

    // check a.txt if you got the expected answer

    return 0;
}
1