简体   繁体   English

存储到我的文件中的结构没有被覆盖(C)

[英]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. 有一个文本文件,其item_name中的名称为Huggies,因此每次运行程序时,都应将Huggies的名称更改为“ Jerb”,但似乎对文件和旧的item_name无效。在文件中保持相同。

I would have thought that if I used the "r+" mode it would overwrite this data in the file but it isn't. 我以为如果使用“ r +”模式,它将覆盖文件中的数据,但事实并非如此。

Help please!! 请帮助!!

Try doing fflush() inside the loop and fclose before exiting. 尝试在循环内执行fflush()并在退出前进行fclose。 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. 调用fwrite()时,将输出写入缓冲区,直到生成4kb的数据为止,并仅在达到4kb或调用fflush / fclose时才将其刷新到文件中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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