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 1

SystemVerilog Testbench Components

$fopen in read versus write mode, checking the returned file descriptor each time, then $fclose.

Open in IDE
testbench.sv
module tb;
  initial begin
  	int fd; 		// Declare an integer variable to hold the file descriptor
    
    // Open a file called "note.txt" in the current folder with a "read" permission
    // If the file does not exist, then fd will be zero
    fd = $fopen ("./note.txt", "r"); 	
    if (fd)
      $display("File was opened successfully : %0d", fd);
    else
      $display("File was NOT opened successfully : %0d", fd);
    
    // Open a file called "note.txt" in the current folder with a "write" permission
    fd = $fopen ("./note.txt", "w"); 	
    if (fd)
      $display("File was opened successfully : %0d", fd);
    else
      $display("File was NOT opened successfully : %0d", fd);
    
    // Close the file descriptor
    $fclose(fd);
  end
endmodule




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

ncsim> run
Open failed on file "./note.txt". No such file or directory
File was NOT opened successfully : 0
File was opened successfully : -2147483645
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.