Using $fflush to Manage File Buffers in Verilog and SystemVerilog

In this article, we’ll explore the $fflush system task in SystemVerilog. This function is essential for ensuring your file operations are efficient and reliable. We'll cover why flushing is necessary, how to use it, and provide a practical example.

Why Do We Need to Flush?

Flushing data to a file in SystemVerilog is useful in several scenarios:

  1. Prevent Data Loss: Writing data goes into a buffer first. If the simulation crashes, buffered data is lost. Using $fflush ensures all buffered data is immediately written to the file, safeguarding your data.
  2. Real-Time Data Access: For real-time processing, flushing ensures that written data is available immediately, rather than waiting for the buffer to fill up.
  3. Effective Debugging: When debugging, you need to see output data right away. Flushing lets you review the latest data instantly, making it easier to diagnose issues.

How to Use $fflush

The $fflush function can be used in three ways:

  • Specific Multi-Channel Descriptor: mcd
  • Specific File Descriptor: fd
  • No Argument: Flushes all open files

Here's the syntax for each usage:

$fflush(mcd); // Flushes the file specified by multi-channel descriptor
$fflush(fd);  // Flushes the file specified by file descriptor
$fflush();    // Flushes all open files

For more details on file descriptors like mcd and fd, check out the File Operations article.

Practical Example

Let's look at an example to illustrate $fflush in action. Suppose we are logging data to a file in a simulation and want to ensure that this data is periodically written to avoid any loss.

module FlushExample;
  integer fd;

  initial begin
    fd = $fopen("output.log", "w");
    if (fd == 0) begin
      $display("Error: Could not open file.");
      $finish;
    end
  end

  always_ff @(posedge clk) begin
    $fwrite(fd, "Simulation time: %0t\n", $time);

    if ($time % 1000 == 0) begin
      $fflush(fd);
    end
  end

  final begin
    $fclose(fd);
  end
endmodule

In this example, we open a file output.log for writing and use $fwrite to log the simulation time at each clock cycle. We then use $fflush(fd) every 1000 cycles to ensure the buffer is written to the file periodically.


Using $fflush in SystemVerilog is essential for managing file buffers efficiently and preventing data loss. By strategically flushing the buffer, you ensure that your critical data is always saved and promptly available. This practice is particularly useful for real-time data processing, debugging, and handling large data volumes in long simulations.