title: How to read data from a serial port and write it to a file
body: <p>I have code written that opens a serial port and also opens a txt log file. I want to write incoming data on the serial port to the log file. My question is how to I or what is the best way to read data from the serial port and write it to a file. I can post the code that opens the serial port and log file if its necessary but I don't want to clutter my questions.</p>
  
  <p>I currently have a while loop which reads data from the serial port into a 32 element char array and then writes it to the file. However, the file contains garbage because it is writing the buffer continuously to the file. </p>
  
  <p>I'd appreciate any advice on how to do this properly. I should really only write when the buffer is full but how do I know what size the buffer should be and what happens if there are buffer overruns for example if I don't read on time.</p>
  
  <pre><code>int i,rdlen, ptr;
  char buf[32];
  
  while( 1 ) {
  
      rdlen = read(fd_serial_port, &amp;buf[ptr], 1); //read data from serial line into buffer
  
      fwrite(buf , 1 , sizeof(buf) , log_file);
  
      fflush(log_file);
  
  }
  </code></pre>
  
  <p>The data coming in from the serial line looks like this and arrives every 2 seconds (if that matters)</p>
  
  <pre><code>Starting Contiki-1cb08a4
  With DriverLib v0.44336
  TI SmartRF06EB + CC26xx EM
   Net: sicslowpan
   MAC: TSCH2
   RDC: nordc
   RF: Channel 25
  [node] id=0, role=6ln
  </code></pre>