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 4

SystemVerilog Testbench Components

The same file write, then reading until $feof in a while loop with $fgets.

Open in IDE
testbench.sv
module tb;
  int 	 fd; 			// Variable for file descriptor handle
  string line; 			// String value read from the file
  
  initial begin
    
    // 1. Lets first open a new file and write some contents into it
    fd = $fopen ("trial", "w");
    
    // Write each index in the for loop to the file using $fdisplay
    // File handle should be the first argument
    for (int i = 0; i < 5; i++) begin
      $fdisplay (fd, "Iteration = %0d", i);
    end
    
    // Close this file handle
    $fclose(fd);
    
    
    // 2. Let us now read back the data we wrote in the previous step
    fd = $fopen ("trial", "r");
    
    while (!$feof(fd)) begin
      $fgets(line, fd);
      $display ("Line: %s", line);
    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

Line: 
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.