Module 6: Verilog for Testbench & Simulation · 6.2 Simulation-Only Constructs

Writing to Files

Console printouts disappear when terminal sessions close. Automated regression suites require persistent log files for archival, automated parsing, and regression comparison against golden reference files. Verilog provides file I/O system tasks that mirror standard C library functions.

Opening and Closing Files

Use $fopen to open files and $fclose to release file resources:

integer log_file;

initial begin
    log_file = $fopen("results.log", "w");
    if (log_file == 0)
        $fatal(1, "Could not open results.log");

    // File operations here

    $fclose(log_file);
end

When called with an access mode ("w", "r", "a"), $fopen returns a 32-bit file descriptor. If the operating system cannot open the file, $fopen returns 0. Always verify that the returned descriptor is non-zero. Use "w" mode to overwrite previous runs and ensure clean execution logs.

Writing Formatted Text to Files

Use $fdisplay and $fwrite to output formatted data:

$fdisplay(log_file, "At %t: input=%h output=%h expected=%h", $time, input_val, actual, expected);
$fwrite(log_file, "Continuation without newline ");

Verilog also defines $fstrobe and $fmonitor for deferred and event-driven file logging.

Multichannel Descriptors: Simultaneous Console and File Output

When called without an access mode string, $fopen returns a multichannel descriptor (MCD). An MCD is a 32-bit bitmask where each set bit represents an open channel:

  • Bit 0 (32'h0000_0001) represents standard console output (stdout).
  • Bits 1 through 31 represent up to 31 concurrently open files.

You can bitwise-OR descriptor bitmasks to direct output to multiple targets simultaneously:

integer log_mcd, both;

initial begin
    log_mcd = $fopen("results.log");      // Multichannel mode without access string
    both    = log_mcd | 32'h0000_0001;    // Bit 0 routes output to console

    $fdisplay(both, "At %t: test %0d PASSED", $time, test_num);
end

Do not mix descriptors. A descriptor opened with "w" is a standard handle and cannot be combined using bitwise-OR.

Reading Formatted Files

Read formatted text data using $fscanf and $feof:

integer input_file;

initial begin
    input_file = $fopen("stimulus.txt", "r");
    while (!$feof(input_file)) begin
        $fscanf(input_file, "%h\n", data_val);
        // Apply data_val to DUT inputs
    end
    $fclose(input_file);
end

For plain hexadecimal memory dumps, use $readmemh (discussed in Article 6.2.4). Use $fscanf when input lines contain mixed text strings and numerical fields.

Logging Testbench Implementation

The following testbench verifies a 4-bit incrementer and logs detailed diagnostic data:

`timescale 1ns / 1ps

module incrementer (
    input  wire [3:0] in,
    output wire [3:0] out
);
    assign out = in + 4'd1;
endmodule

module tb_incrementer();

    reg  [3:0] test_in;
    wire [3:0] test_out;

    integer log_mcd, log_and_console;
    integer error_count, test_count;
    integer i;
    reg [3:0] expected;

    incrementer dut (.in(test_in), .out(test_out));

    initial begin
        $dumpfile("tb_incrementer.vcd");
        $dumpvars(0, tb_incrementer);
        $timeformat(-9, 0, " ns", 8);

        log_mcd = $fopen("results.log");
        if (log_mcd == 0)
            $fatal(1, "Cannot open results.log");
        log_and_console = log_mcd | 32'h1;

        $fdisplay(log_mcd, "=== Incrementer Test Results ===");

        error_count = 0;
        test_count  = 0;

        for (i = 0; i < 16; i = i + 1) begin
            test_in  = i[3:0];
            expected = i[3:0] + 4'd1;      // Wraps to zero upon overflow
            #10;
            test_count = test_count + 1;

            if (test_out !== expected) begin
                $fdisplay(log_and_console, "%t  in=%0d  expected=%0d  got=%0d  FAIL",
                          $time, test_in, expected, test_out);
                error_count = error_count + 1;
            end else begin
                $fdisplay(log_mcd, "%t  in=%0d  expected=%0d  got=%0d  pass",
                          $time, test_in, expected, test_out);
            end
        end

        if (error_count == 0)
            $fdisplay(log_and_console, "RESULT: PASSED, all %0d tests.", test_count);
        else
            $fdisplay(log_and_console, "RESULT: FAILED, %0d of %0d tests.", error_count, test_count);

        $fclose(log_mcd);
        $finish;
    end

endmodule

In this architecture, failures log to both the console and the output file. Passing vectors log only to the file, keeping console output uncluttered.

Automated regression scripts compare the resulting log against reference files:

diff results.log golden_results.log && echo "Regression PASSED" || echo "Regression FAILED"

Use relative filenames so simulations write files into the local execution directory.

The next article examines $readmemh and $readmemb for loading memory arrays and test vectors from external files.

← $finish, $stop and Time $readmemh and $readmemb →