1

So this is my first question here. I'm rather new to both programming and the language C, but if you could help me, that would be much appreciated. In school we have an assignment. I have spoken to a few students in my class, and they use Code blocks, while I use Visual Studio. So I'm trying to write to a file, and it works for one of my friends in Code blocks, and I've tried to do exactly the same (but in visual studio, so I have to use fopen_s instead of fopen) but I can't make it work.

My function, which is supposed to write some items on a grocery list to a file - looks like this:

FILE* file = 0; 
char filename[25];

printf("Saving grocery list to test.bin...\n"); 

The line below is what is different from my friend's code

errno_t errorCode = fopen_s(&file, "test.bin", "wb"); //This line is different 
//because of MVS...

if (file == NULL )
{
    printf("File could not be opened.\n"); 
    return 0; 
}

else
{
    fwrite(&totalGrocery, sizeof(int), totalGrocery, file);
    fwrite(&item, sizeof(struct grocery), totalGrocery, file);
    fclose(file);
    printf("The file has now been saved.\n"); 
}

Okay, so my file that I want to save to is named "test.bin", my grocery list is saved in a struct (called grocery), where item is a pointer to the first item in my grocery list (struct grocery *item) and totalGrocery is my variable for how many struct grocery item that I have saved.

If it's needed, this is what my struct grocery looks like

struct grocery  
{
    int id;
    char food[31];
    float quantity;
    char unit[16]; 
};

And every item is made up of one of these struct grocery.

I hope I made myself clear... Nothing is crashing or anything, but it seems my file never gets anything from the program.

Have I written the fopen_s function wrong? I can't find a lot of information anywhere how it supposed to be written, so I think this might be the case...?

  • 3
    Relate: this is likely wrong: `fwrite(&totalGrocery, sizeof(int), totalGrocery, file);` The second paramter should be `sizeof(totalGrocery)`, the third parameter **`1`**. Secondly, "it seems my file never gets anything from the program" - assuming you *found* the correct file on your file system (it would be in your project folder if you ran this from the VS IDE), how *exactly* are you assessing that nothing was written to it? Checking its size on-disk? Opening it in an editor? How? – WhozCraig Oct 21 '16 at 20:18
  • `fopen_s(&file, "test.bin", "wb");` Have you tried just `"w"` for the open mode? – Keith M Oct 21 '16 at 20:32
  • Could you show [MCVE] please? – Jabberwocky Oct 21 '16 at 21:42
  • On this step, it makes sense to use the same IDE which all the other classmates use. When you are confident in the language and tools, you can afford being different. – ddbug Oct 22 '16 at 00:37

0 Answers0