[SV]SystemVerilog文件讀寫案例

       摘要:

一、讀取文件內容并打印出來:

program read_file();
  integer    f;
  string     key;

  reg [31:0]    value;
  reg [31:0]    hash [string];

  initial begin : file_read
    f = $fopen("file.txt", "r");
    if(f == 0) disable file_read;

    while(!feof(f)) begin
      $fscanf(f, "%s %h\n", key, value);   //$fscanf裡面的格式控制符與文件格式要Match
      hash[key] = value;
    end

    foeeach(hash[i]) begin
      $display("Hash Key %0s --> %0h", i hash[i])
    end

endprogram

二、把讀文件封裝成一個module。

module openfile#(
  parameter FILE    = "txt",
  parameter DW      = 32,
  parameter PN      = 32
)
(
  input bit            rst_b,
  input bit            clk,
  input bit            pop_str,
  input bit [DW-1:0]   out_i
)

  integer              int_ifptr, int_count;
  reg signed [31:0]    data_i_scan[0:PN-1];
  integer              data_i_tmp[$];
  reg                  dout_i;

  initial begin : open_file
    repeat(10) @(posedge clk);
    int_ifptr = $fopen($sformatf(FILE), "r");
    for(int i = 0; i < PN; i = i + 1) begin
      int_count = $fscanf(int_ifptr, "%0h\n", data_i_scan[i]);
      data_i_tmp.push_back(data_i_scan[i]);
    end
    $fclose(int_ifptr);
  end

  always @(posedge clk or negedge rst_n) begin
    if(!rst_n) begin
      dout_i <= {32{1'b0}};
    end
    else if(data_i_tmp.size() != 0) begin
      if(pop_str) begin
        dout_i <= data_i_tmp.pop_front();
      end
    end
  end

  assign out_i = d_out_i[DW-1:0];

endmodule
发布了140 篇原创文章 · 获赞 81 · 访问量 4万+

猜你喜欢

转载自blog.csdn.net/gsjthxy/article/details/103887334