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 Operations Example 5

SystemVerilog Testbench Components

The same file write, then parsing each line with $fscanf("%s = %0d", ...) and using its match count as the loop condition.

Open in IDE
testbench.sv
//--------------------------------------------------------------
// Author  : Admin, ChipVerify
// Website : www.chipverify.com
//--------------------------------------------------------------

module tb;
  int 	 fd; 			// Variable for file descriptor handle
  int 	 idx;
  string str;
  
  
  initial begin
    
    // 1. Lets first open a new file and write some contents into it
    fd = $fopen ("trial", "w");
    for (int i = 0; i < 5; i++) 
      $fdisplay (fd, "Iteration = %0d", i);
    $fclose(fd);
    
    
    // 2. Let us now read back the data we wrote in the previous step
    fd = $fopen ("trial", "r");
    
    // fscanf returns the number of matches
    while ($fscanf (fd, "%s = %0d", str, idx) == 2) begin
      $display ("Line: %s = %0d", str, idx);
    end
    
    // Close this file handle
    $fclose(fd);
  end
endmodule



/*
Simulation Log:
---------------

ncsim> run
Line: Iteration = 0
Line: Iteration = 1
Line: Iteration = 2
Line: Iteration = 3
Line: Iteration = 4
ncsim: *W,RNQUIE: Simulation is complete.
ncsim> exit
*/
design.sv
// Code your design here
Admin mode — edit and delete controls are visible on each row. Use the IDE to add new snippets via File → Save as Snippet.