Verilog File I/O

File operations are essential for loading test vectors, initializing memories, and logging simulation results.

Reading Memory Files

The most common file operation is loading ROM/RAM contents:

$readmemh and $readmemb
module rom_tb;
    reg [7:0] memory [0:255];  // 256 x 8-bit memory
    initial begin
        // Load hex file (each line = one memory word)
        $readmemh("rom_data.hex", memory);
        // Or binary file
        $readmemb("rom_data.bin", memory);
        // With start/end address
        $readmemh("data.hex", memory, 0, 127);  // Load to first half
    end
endmodule
// Example rom_data.hex file:
// @00    // Optional: start address
// AB
// CD
// 12
// 34

File Format

Each line contains one value. Use @address to set load address. Comments use //.

Writing to Files

File Write Operations
module logger_tb;
    integer log_file;
    reg [7:0] data;
    integer i;
    initial begin
        // Open file for writing
        log_file = $fopen("simulation.log", "w");
        if (log_file == 0) begin
            $display("ERROR: Could not open file!");
            $finish;
        end
        // Write formatted data
        $fwrite(log_file, "Simulation Log\n");
        $fwrite(log_file, "==============\n\n");
        for (i = 0; i < 10; i = i + 1) begin
            data = $random;
            $fwrite(log_file, "Time=%0t Data=0x%02h\n", $time, data);
            #10;
        end
        // Close file
        $fclose(log_file);
        $display("Log file written successfully");
        $finish;
    end
endmodule

Reading Test Vectors

Reading Stimulus from File
module stimulus_tb;
    integer file, status;
    reg [7:0] a, b;
    reg [8:0] expected_sum;
    initial begin
        file = $fopen("test_vectors.txt", "r");
        while (!$feof(file)) begin
            // Read formatted input
            status = $fscanf(file, "%h %h %h\n", a, b, expected_sum);
            if (status == 3) begin  // Successfully read 3 values
                #10;
                $display("a=%h b=%h expected=%h", a, b, expected_sum);
            end
        end
        $fclose(file);
        $finish;
    end
endmodule
// test_vectors.txt:
// 0A 14 1E
// FF 01 100
// 00 00 00

Common Interview Questions

  1. What's the difference between $readmemh and $readmemb?

    $readmemh reads hexadecimal values; $readmemb reads binary values.

  2. Can you use file I/O in synthesizable code?

    No. All file operations are for simulation only.

  3. How do you check if a file opened successfully?

    $fopen returns 0 on failure. Always check the return value.