File Operations in verilog Test-Bench.

$fopen, $fclose, $fdisplay, $fscanf are discussed on this page with examples.

External files are called in test-benches for reading in vectors and storing results of simulations for further analysis. Most of the key operations involved in handling external files are discussed below with examples.

How to open a file to read text:
read_file = $fopen(“readme.txt”, r);
The highlighted text in blue is used to show the command which will tell Verilog compiler to read the text file readme.txt.

How to Open a file to write text:
write_file = $fopen(“readme.txt”, w);
The highlighted text in blue is used to show the command which will tell Verilog compiler to write to the text file readme.txt after erasing all the data from it. Other similar option wb.

LTE - 4G Wireless Technology

Digital fundamentals.

Interview Questions.

How to Open a file to append text.
append_file = $fopen(“readme.txt”, a);
The highlighted text in blue is used to show the command which will tell Verilog compiler to open the text file readme.txt and append more text at the end of the file. Other similar option ab.

How to Open a file to both read and write text.
rw_file = $fopen(“readme.txt”, r+);
The highlighted text in blue is used to show the command which will tell Verilog compiler to open the text file readme.txt to enable both reads and writes to it. Other similar option r+b or rb+.

How to Close or release an open file.
$fclose(readme.txt);

Reading text in specified format from opened file. ( Supported in Verilog-2001)
Read the data in specified format (hexadecimal, binary or octal) and store it in a register.
read_data = $fscanf(read_file, “%format”, register_to_store_data);

Tutorials @fullchipdesign.com

Verilog Tutorial.

LTE Tutorial.

Memory Tutorial.

~\Documents\fullchip\python\mysite\webpages\templates\webpages\test.v.html
Example Verilog code snippet to do file operations
module tb ();
// reg and wire declarations
................................
always @(posedge clk or
   negedge rst)
begin
   if (!rst)
   begin
     q_cnt <= 0;
    write_data <= 'b0;
    out = $fopen("mem_ram.vec","w");
    rout = $fopen("mem_ram_read.vec","w");
   end
   else begin
       if (q_cnt < 63)  begin
           q_cnt <= q_cnt+1;
           write_data <= $random(seed) & 'hFF;
           read_rq <= 0;
           write_rq <= 1;
           rw_address <= q_cnt;
           $fdisplay(out, "Address::%d:: %b :: -- contents in hex %h", rw_address, write_data, write_data);
       end
       else begin
           q_cnt <= q_cnt;
           write_data <= write_data;
           rw_address <= $random(seed) & 'h3F;
           read_rq <= 1;
           write_rq <= 0;
           $fdisplay(rout,"Address::%d:: %b :: -- read contents in hex %h", rw_address, read_data, read_data);
end end end
................................
endmodule

Hope you liked! this page. Don't forgot to access relevant previous and next sections with links below.