简体   繁体   中英

The struct that is stored to my file isn't being Overwritten ( C )

#include <stdio.h>
#include <string.h>

typedef struct batch
{
  int month;
  int day;
  int qty;
  float item_cost;
  int batch_num;
} BATCH;

struct stock
{
  char item_name[50];
  int t_qty;
  float t_item_cost;
  int item_code;
  BATCH batch[10];
  int last_batch_num;
  float price_for_one;
  float price;
};

int main()
{
   FILE *filepointer;
   filepointer = fopen("stocklist.txt", "r+");

   struct stock loop;

   while(fread(&loop, sizeof(struct stock), 1, filepointer))
   {
       printf("%s\n", loop.item_name);
       strcpy(loop.item_name, "Jerb");
       printf("%s\n", loop.item_name);

       fwrite(&loop, sizeof(struct stock), 1, filepointer);
    }
}

There is a text file which has in an item_name which is Huggies, so every time I run the program it should change the name of Huggies to "Jerb" but it seems that it isn't having any effect on the file and the old item_name stays in the same in the file.

I would have thought that if I used the "r+" mode it would overwrite this data in the file but it isn't.

Help please!!

Try doing fflush() inside the loop and fclose before exiting. When fwrite() is called, the output is written to a buffer until 4kb of data is generated and flushed to the file only when it reaches 4kb or when fflush/fclose is called.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM