Search code examples
cfputs

How to write a datastructure to a file with fput in c?


What i have here is a struct that i want to print to a file. The structure consists of a series of singel character ints where pek3 Points at the first object containing a number in the structure.

fprintf didnt work and this just gives me the error:

missing ')' Before '->'

FILE *filen;
 int h;
            talstrul *tepek = pek3;
            filen = fopen("summadata.txt","w");
            for(h=1; h<=maxlen; h++)
            {   int fput(tepek->num,filen);
                tepek = tepek->next;
            }
            fclose(filen);

Solution

  • Your example is incomplete - so we have to guess.

    f = fopen("summadata.txt","w");
    for(int h=1; h<=maxlen; h++) {
        fprintf(f, "%d\n", tepek->num);    
        tepek = tepek->next;
    }
    fclose(f);
    

    should work.

    fprintf works as follows:

    • the first argument is the file handle, that is what you get from fopen.
    • the format string, here "%d\n", describes, what you want to print. Here it is a integer ("%d") and then a newline ("\n").
    • then comes the arguement(s) to the formatstring. In this case the integer, I guess that is tepek->num.