Chip Designing for ASIC/ FPGA Design engineers and Students
Digital-logic Design... Dream for many students… start learning front-end…
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.
Example Verilog code snippet to do file operations
module tb ();
// reg and wire declarations
always @(posedge clk or
q_cnt <= 0;
write_data <= 'b0;
out = $fopen("mem_ram.vec","w");
rout = $fopen("mem_ram_read.vec","w");
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);
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
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.
$fopen, $fclose, $fdisplay, $fscanf are discussed on this page with examples
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);
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.
Writing text into the opened file.
Write to file starting at a new line.