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

时间:2019-01-26 13:08:07

标签: c arrays pointers fopen fgets

我有一个给定的结构。我读取了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);    

    } 

最后一个输出是:“刚刚在第22行中写了char Nr。36”

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

1 个答案:

答案 0 :(得分:3)

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

顺便说一句:如果您的行以null结尾,则可以使用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);