Search code examples
carrayspointersfopenfgets

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


I have a given structure. I read all the characters of a txt-file and save it to a multidimensional array (lines) that i defined within the struct. Then I want to hand the struct variable over to a function which should then print all the characters to another txt-file.

Thats what I have:

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);    

    } 

The last output is: "just wrote char Nr. 36 in line: 22"

But the last char written into the file is Nr 0 in line 10...


Solution

  • You are using a pointer to your struct so you need to use fputc(content->lines[curline][curchar], pFile).

    Btw: If your lines are null-terminated you can use fputs(content->lines[curline], pFile)

    Also @Someprogrammerdude is right you should define write_content prior to calling it.

    Refering to the comments:

    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);