Search code examples
vhdl

Is it possible to check the length of an input text file?


In my VHDL project, my input is going to be extracted from a text file containing n bits of 1's and 0's. I am trying to make it as general as possible. I am familiar with how to read and write on a text file using test-bench, but I don't know how to check its length.

My code normally takes 64 bit as input, pass them through all the blocks and generate an output. If the remaining bits length is less than 64 then it passes through a specific block.

Let's say the text file contains 1000 bits. 15 x 64 = 960. 960 bits will pass through all blocks, the remaining 40 will pass by a specific block. This looks straight forward but in order for me to do such operations i need to know the length of the text file. If anyone can help that would be very beneficial.


Solution

  • The VHDL data structure length should be considered, not the file length since that is implementation specific and not VHDL specified.

    If the bits are in one long string that is to be chopped up into 64-bit pieces with a remainder, then the entire string can be read into a VHDL line type, and reading from that line to a std_logic_vector type can then depend on the remaining bits (characters) in the line.

    Below is a code example doing so:

    library ieee;
    use std.textio.all;
    use ieee.std_logic_textio.all;  -- Synopsys package; required for VHDL-2002 only
    
    architecture syn of tb is
    begin
      process is
        variable myl_v : line;
        file txt_file : text;
        variable slv_v : std_logic_vector(63 downto 0);
      begin
        file_open(txt_file, "input.txt", read_mode);
        readline(txt_file, myl_v);
        while myl_v'length > 0 loop
          if myl_v'length >= slv_v'length then  -- Full slv_v
            report "Full...: " & myl_v.all(1 to slv_v'length);
            read(myl_v, slv_v);
          else  -- Reduced slv_v
            report "Reduced: " & myl_v.all(1 to myl_v'length);
            read(myl_v, slv_v(myl_v'length - 1 downto 0));  -- Place reduced at LSBs
          end if;
        end loop;
        file_close(txt_file);
        wait;
      end process;
    end architecture;
    

    Btw, to answer the question of "length of an input text file", then the length in characters can be determined by reading as many characters from the file as possible, for example with code like:

    impure function file_length_in_characters(filename : string) return natural is
      type char_file_t is file of character;
      file char_file : char_file_t;
      variable char_v : character;
      variable res_v : natural;
    begin
      res_v := 0;
      file_open(char_file, filename, read_mode);
      while not endfile(char_file) loop
        read(char_file, char_v);
        res_v := res_v + 1;
      end loop;
      file_close(char_file);
      return res_v;
    end function;