在Verilog中,文件读取和写入是非常有用的。从文件中读取测试激励输入,并写入输出以供比对。
在Verilog中读取或写入文件的方法很少。
- 如何使用readmemh函数从文件中读取十六进制值。
- 如何使用readmemb函数从文件中读取二进制值。
- 如何使用fopen和fdisplay写入二进制值的文件。
- 如何使用fopen和fdisplay写入十进制值的文件。
- 如何使用fopen和fdisplay写入十六进制值的文件。
文件读写Verilog代码:
`timescale 1ns / 1ps
module tb();
reg [7:0] A [0:15]; //memory declaration for storing the contents of file.
integer outfile1,outfile2,outfile3; //file descriptors
integer i; //index used in "for" loop
initial begin
//read the contents of the file A_hex.txt as hexadecimal values into memory "A".
$readmemh("A_hex.txt",A);
//The $fopen function opens a file and returns a multi-channel descriptor
//in the format of an unsized integer.
outfile1=$fopen("A_write_dec.txt","w");
outfile2=$fopen("A_write_bin.txt","w");
outfile3=$fopen("A_write_hex.txt","w");
//Write one by one the contents of vector "A" into text files.
for (i = 0; i < 16; i = i +1) begin
$fdisplay(outfile1,"%d",A[i]); //write as decimal
$fdisplay(outfile2,"%b",A[i]); //write as binary
$fdisplay(outfile3,"%h",A[i]); //write as hexadecimal
end
//once writing is finished, close all the files.
$fclose(outfile1);
$fclose(outfile2);
$fclose(outfile3);
//wait and then stop the simulation.
#100;
$stop;
end
现在,如果您想读取二进制文件而不是十六进制文件,您只需要替换上述代码中的一行,
替换
$readmemh("A_hex.txt",A);
为
$readmemb("A_bin.txt",A);
就在这两种情况下,输出文件看起来都是一样的。输入文件和输出文件的屏幕截图如下: