如何将结构的内容保存到 C 文件中?

How to save the content of a structure to a file in C?

我有给定的结构。我读取了一个 txt 文件的所有字符并将其保存到我在结构中定义的多维数组(行)。然后我想将 struct 变量交给一个函数,然后该函数应该将所有字符打印到另一个 txt 文件。

这就是我所拥有的:

typedef struct _content {
    int length;
    char **lines;    // multidimensional array
} content_t;


int curline = 0;     //global variables
int curchar = 0;

...

struct _content inhalt;
c = fgetc(ptr);

...

void write_content(char *filename, content_t *content)
{
    FILE *pFile;
    pFile = fopen(filename, "a");

    printf("\nWriting Char Nr. %d in line: %d", curchar, curline);

    fputc(content->lines[curline][curchar], pFile);

    printf("\nJust wrote char Nr. %d in line: %d !", curchar, curline);

}



...


    while(c != EOF)     
    {
        inhalt.lines[curline][curchar] = c;

        //where I call the function write_content:
        write_content("write-file.txt", &inhalt);

        if(c == '\n')      
        {
            inhalt.length++;      
            curline++;      
            inhalt.lines[curline] = malloc(255);
            curchar = 0;
        }
        else
        {
        curchar++;
        }
        c = fgetc(ptr);     
        printf("%c", c);    

    } 

最后的输出是:"just wrote char Nr. 36 in line: 22"

但是写入文件的最后一个字符是第 10 行的 Nr 0...

您正在使用指向您的结构的指针,因此您需要使用 fputc(content->lines[curline][curchar], pFile)

顺便说一句:如果你的行是空终止的,你可以使用 fputs(content->lines[curline], pFile)

@Someprogrammerdude 也是对的,你应该在调用它之前定义 write_content

参考评论:

void write_content(char *filename, content_t *content)
{
    FILE *pFile;
    pFile = fopen(filename, "a");

    for(int line = 0; line <= curline; line++){
        for(int c = 0; content->lines[line][c] != 0; c++){ // because 0 terminates the string
            printf("\nWriting Char Nr. %d in line: %d", c, line);
            fputc(content->lines[line][c], pFile);
        }
    }
    fclose(pFile);

}
// ...

while(c != EOF){
    inhalt.lines[curline][curchar] = c;

    if (c == '\n')      
    {
        inhalt.lines[curline][curchar+1] = 0; // ensure null termination
        inhalt.length++;      
        curline++;      
        inhalt.lines[curline] = malloc(255);
        curchar = 0;
    }
    else
    {
        curchar++;
    }
    c = fgetc(ptr);     
    printf("%c", c);    
} 
//where I call the function write_content:
write_content("write-file.txt", &inhalt);