clinked-listfopenfwritefread

Integer File Not Opening Correctly


I apologize that this is probably a question with a very simple explanation, but I can't seem to find it. I'm currently trying to build a basic database with C. I need to save a structure-linked list along with the size of said linkededlist, so that I know how large the list is, when I open it. I'm planning to write the size of the list as an integer, along with the linkedlist. For some reason, even with the linked list commented out, the program fails to read the file. The relevant code is below:

#define Opennamefile Movienames=fopen("movienames.txt", "wb")
#define Closenamefile fclose(Movienames)
FILE *Movienames=NULL;

int openfile(int *flistsize)
{
int reject=0;
Opennamefile;
if((fread(&flistsize, sizeof(int), 1, Movienames))!=1) reject=-690;
//if(fread(&head, sizeof(identity), flistsize, Movienames)!=1) reject=-690;
if((Movienames==NULL) || (reject==-690))
{
fputs("Error opening the name file\n", stderr);
printf("%d", *flistsize);
}

return 1;
}

int savenamefile(int flistsize)
{
    int reject=0;
    if(fwrite(&flistsize, sizeof(int), 1, Movienames)!=1) reject=-690;
    //if(fwrite(&head, sizeof(identity), flistsize, Movienames)!=flistsize) reject=-690;
Closenamefile;
    if(Movienames==EOF || reject==-690)
    {
        fputs("Error closing file", stderr);
        return -69;
    }
    puts("successfully closed/saved file");
    return 1;
}

Solution

  • In your openfile function, flistsize is already a pointer to the target that you want to write to. But you are referencing that again, meaning you'll be writing to the memory that holds the pointer value itself.

    To fix that issue, remove the &:

    fread(flistsize, sizeof(int), 1, Movienames)