Ready-to-run snippets

Code Examples

Ready-to-run Verilog, SystemVerilog, and UVM examples. Click any to open it live in the IDE.

← All examples

File IO Operations: How to write files

Verilog Examples

Runnable example from the Verilog File IO Operations tutorial (How to write files)

Open in IDE
testbench.v
module tb;
  integer   fd;
  integer   i;
  reg [7:0] my_var;

  initial begin
    // Create a new file
    fd = $fopen("my_file.txt", "w");
    my_var = 0;

    $fdisplay(fd, "Value displayed with $fdisplay");
    #10 my_var = 8'h1A;
    $fdisplay(fd, my_var);      // Displays in decimal
    $fdisplayb(fd, my_var);     // Displays in binary
    $fdisplayo(fd, my_var);     // Displays in octal
    $fdisplayh(fd, my_var);     // Displays in hex

    // $fwrite does not print the newline char '\n' automatically at
    // the end of each line; So we can predict all the values printed
    // below to appear on the same line
    $fdisplay(fd, "Value displayed with $fwrite");
    #10 my_var = 8'h2B;
    $fwrite(fd, my_var);
    $fwriteb(fd, my_var);
    $fwriteo(fd, my_var);
    $fwriteh(fd, my_var);

    // Jump to new line with '\n', and print with strobe which takes
    // the final value of the variable after non-blocking assignments
    // are done
    $fdisplay(fd, "\nValue displayed with $fstrobe");
    #10 my_var <= 8'h3C;
    $fstrobe(fd, my_var);
    $fstrobeb(fd, my_var);
    $fstrobeo(fd, my_var);
    $fstrobeh(fd, my_var);

    #10 $fdisplay(fd, "Value displayed with $fmonitor");
    $fmonitor(fd, my_var);

    for(i = 0; i < 5; i= i+1) begin
      #5 my_var <= i;
    end

    #10 $fclose(fd);
  end
endmodule
Admin mode — edit and delete controls are visible on each row. Use the IDE to add new snippets via File → Save as Snippet.