Search code examples
vhdlfpga

"Readline called past the end of file" error VHDL


I need to read a file in VHDL but there is an error: "Line 57: Readline called past the end of file mif_file"

impure function init_mem(mif_file_name : in string) return mem_type is
    file mif_file : text open read_mode is mif_file_name;
    variable mif_line : line;
    variable temp_bv : bit_vector(DATA_WIDTH-1 downto 0);
    variable temp_mem : mem_type;
begin
    for i in mem_type'range loop
        readline(mif_file, mif_line);
        read(mif_line, temp_bv);
        temp_mem(i) := to_stdlogicvector(temp_bv);
    end loop;       
return temp_mem;
end function;

Solution

  • As stated in the comment section, you are trying to read more than you have in the file, you can avoid the error by checking if you reached the end of the file in your for loop and in that case assign a default value instead.

    impure function init_mem(mif_file_name : in string) return mem_type is
        file mif_file : text open read_mode is mif_file_name;
        variable mif_line : line;
        variable temp_bv : bit_vector(DATA_WIDTH-1 downto 0);
        variable temp_mem : mem_type;
    begin
        for i in mem_type'range loop
            if(not endfile(mif_file)) then
                readline(mif_file, mif_line);
                read(mif_line, temp_bv);
                temp_mem(i) := to_stdlogicvector(temp_bv);
            else
                temp_mem(i) := default_value_to_be_defined;
            end if;
        end loop;       
    return temp_mem;
    end function;
    

    Or you can exit the for loop if you don't want to set a default value

    impure function init_mem(mif_file_name : in string) return mem_type is
        file mif_file : text open read_mode is mif_file_name;
        variable mif_line : line;
        variable temp_bv : bit_vector(DATA_WIDTH-1 downto 0);
        variable temp_mem : mem_type;
    begin
        for i in mem_type'range loop
            if(not endfile(mif_file)) then
                readline(mif_file, mif_line);
                read(mif_line, temp_bv);
                temp_mem(i) := to_stdlogicvector(temp_bv);
            else
                exit;
            end if;
        end loop;       
    return temp_mem;
    end function;