0

I use c++ stream to write content into file, and i found only when file size hit 4k*n, the content will be written into file, else it will miss, can anyone explain this?

please see the following code:

#include "../order.h"
#include <iostream>
#include <string>

using namespace std;

int main() {
  string s;
  std::ofstream f;
  f.open("test.log", ios::out); //  | ios::app);// | ios::binary);
  while (cin >> s && s != "quit") {
    Order o;
    snprintf(o.contract, sizeof(o.contract), "%s", s.c_str());
    o.Show(f);
  }
  f.close();
}

order.h

#include <stdio.h>
#include <sys/time.h>
#include <fstream>
struct Order {
  timeval shot_time;
  timeval send_time;
  char contract[MAX_CONTRACT_LENGTH];
  double price;
  int size;
  int traded_size;
  OrderSide::Enum side;
  char order_ref[MAX_ORDERREF_SIZE];
  OrderAction::Enum action;
  OrderStatus::Enum status;
  Offset::Enum offset;
  char tbd[128];

  Order()
    : size(0),
      traded_size(0),
      offset(Offset::UNINITED) {
    snprintf(tbd, sizeof(tbd), "%s", "null");
  }

  void Show(std::ofstream &stream) const {
    stream.write((char*)this, sizeof(*this));
  }
}

when i loop to cin, file size added only when content is 4k*n, how can i avoid the miss of message?

nick huang
  • 443
  • 4
  • 12
  • 1
    How do you check the file size? And what is `Order`? What is `sizeof(Order)`? Please create a [mcve] to show us. – Some programmer dude Oct 21 '19 at 10:50
  • 2
    Or is the problem simply that the output is ***buffered***? Have you tried [flushing](https://en.cppreference.com/w/cpp/io/basic_ostream/flush) the buffer? – Some programmer dude Oct 21 '19 at 10:51
  • 1
    `#include "../order.h"`: Please post the minimal complete code, its likely the stuff from order you ommited cause the problem. Even if not, you should eliminate it, then you know for sure and you problem is minimalized. – Superlokkus Oct 21 '19 at 10:53
  • @Someprogrammerdude added the order defination, sorry for that – nick huang Oct 21 '19 at 10:55
  • @Superlokkus added the order.h, sorry for the uncosiderate code commit – nick huang Oct 21 '19 at 10:56
  • Once you close the stream all the data should be written into the file. You can achieve what you want if you flush the stream with `stream.flush()` after writing to it. – Lukas-T Oct 21 '19 at 11:05
  • Output streams are buffered by default. See the linked question for more information. – Sam Varshavchik Oct 21 '19 at 11:13

0 Answers0