Search code examples
file-ioverilog

How to read a text file line by line in verilog?


I have a SREC file which is a simple text file and I want to read it line by line in verilog. How can I do that?


Solution

  • The following reads through a file, 1 line per clock cycle: expected data format is one decimal number per line.

    integer               data_file    ; // file handler
    integer               scan_file    ; // file handler
    logic   signed [21:0] captured_data;
    `define NULL 0    
    
    initial begin
      data_file = $fopen("data_file.dat", "r");
      if (data_file == `NULL) begin
        $display("data_file handle was NULL");
        $finish;
      end
    end
    
    always @(posedge clk) begin
      scan_file = $fscanf(data_file, "%d\n", captured_data); 
      if (!$feof(data_file)) begin
        //use captured_data as you would any other wire or reg value;
      end
    end