常见函数:

$bitstoreal, $rtoi, $display, $setup, $finish, $skew, $hold, $setuphold, $itor, $strobe, $period, $time, $printtimescale, $timeformat, $real, $width, $realtobits, $write, $recovery

fopen

1
2
integer file_id;
file_id = $fopen("file_path/file_name");

fwrite

1
2
3
4
5
6
7
8
9
10
// 只要有变化就记录
$fmonitor(file_id, "%format_char", parameter_list);
$fmonitor(file_id, "%m: %t in1 = %d o1 = %h", $time, in1, o1);

// 需要触发条件才记录
$fwrite(file_id, "%format_char", parameter_list);

// 需要触发条件才记录
$fdisplay(file_id, "%format_char", parameter_list);
$fstrobe();

fread

1
2
integer file_id;
file_id = $fread("file_path/file_name", "r");

fclose

1
$fclose(file_id);

readmemh / readmemb

1
2
$readmemh("file_name", memory_name);    // hex
$readmemb("file_name", memory_name); // bin

feek

1
2
3
4
5
6
7
8
9
10
`define SEEK_SET 0
`define SEEK_CUR 1
`define SEEK_END 2

integer file, offset, position, r;

r = $fseek(file, 0, `SEEK_SET);
r = $fseek(file, 0, `SEEK_CUR);
r = $fseek(file, 0, `SEEK_END);
r = $fseek(file, position, `SEEK_SET);

ftell

1
2
integer file, position;
position = $ftell(file);

sformat

1
2
3
4
5
6
integer file, r, a, b;
reg [80*8:1] string;
file = $fopenw("output.log");
r = $sformat(string, "Formatted %d %x", a, b);
r = $sprintf(string, "Formatted %d %x", a, b);
r = $sprintf(file, "Formatted %d %x", a, b);

读数据到存储器

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
`define EOF 32'HFFFF_FFFF
`define MEM_SIZE 200_000

module load_mem;
integer file, i;
reg [7:0] mem[0:`MEM_SIZE];
reg [80*8:1] file_name;
initial begin
file_name = "data.txt";
file = $fopenr(file_name);
i = $fread(file, mem[0]);
$display("Loaded %0d entries \n", i);
i = $fcloseer(file);
$stop;
end
endmodule

自动比较结果

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
`define EOF 32'HFFFF_FFFF
`define NULL 0
`define MAX_LINE_LENGTH 1000

module compare_result;
integer file, r;
reg a, b, expect_v, clock;
wire out;
parameter cycle = 20;

always #(cycle/2) clock = !clock;

initial begin: file_block
clock = 0;
file = $fopen("compare.pat");
if (file == `NULL) disable file_block;

while (!$feof(file)) begin
@ (posedge clock)
r = $fscanf(file, " %b %b %b\n", a, b, expect_v);
#(cycle - 1) $display("%d %b %b %b %b", $stime, a, b, expect_v, out);
$strobe_compare(expect_v, out);
end

r = $fcloser(file);
$stop;
end

DUT U_dut(.a(a), .b(b), .out(out));
endmodule