Testbench learning - $fopen/$display/$fclose

When I used Vivado to write the top layer of Testbench yesterday, in order to facilitate data storage and export analysis in the future, I needed the function of file data recording. Therefore, let's talk about the usage of $fopen/$display/$fclose.

$fopen - open file

Usage 1: $fopen("<file name>");

Usage 2: <file handle> = $fopen("<filename>");

$fdisplay - write file

Usage: $fdisplay(<file descriptor>,p1,p2,...pn);

$fclose - close the file

Usage: $fclose(<file descriptor>);

 

Example

integer handle; // Define variables to be used later
 // ...
 // ... 
 
handle = $fopen( " data.txt " ); // Open file
 // ...
 // ... 
always # 10 clk = ~clk; // Define the clock 
always # 20 
begin 
    $fdisplay(handle, " %d " ,rand_num); // Write data 
    while (!rst_n) $fclose(handle); // Close the file 
end

 

Example:

//test $fopen
integer handle;
initial begin
handle = $fopen("../data.txt");
end

reg [7:0]test_cnt;
always @ (posedge sys_clk)
begin
    if (sys_rst)
        test_cnt <= 8'h0;
    else if (test_cnt == 8'h1E)
        test_cnt <= test_cnt;
    else if (fix_timer_o[1])
        test_cnt <= test_cnt + 1'b1;
    else
        test_cnt <= test_cnt;
end

always @ (posedge fix_timer_o[1])
    if (test_cnt == 8'h1E)
        $fclose(handle);
    else
        $fdisplay(handle,"%d",test_cnt);

    // else if (fix_timer_o[1])
        // $fdisplay(handle,"%d",test_cnt);
    // else
    // ;    
endmodule

 

Remark:

1. When using $fopen in Vivado, it needs to be called in the initial, otherwise Critical Warnning will appear (may not have this problem in Modelsim);

2. The file will be written and saved only after the $fclose statement is executed;

3. The output file is under a XX.sim folder of the project. There are posts on the Internet saying that the storage path of the output file cannot be specified or cannot be specified with a relative path.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324879097&siteId=291194637