VHDL coding tips and tricks: Reading and writing real numbers using Files - Part 3

Friday, January 13, 2012

Reading and writing real numbers using Files - Part 3

After the previous posts on file handling, now I have come up with another way to read and write files.

In this article I will show how to read a text file containing real numbers and store the square roots of these real numbers in another text file. The input file is named as "1.txt" and output file is named as "2.txt".

Contents of 1.txt:

12.23
34.4343
23.11
5.0
25.0
49.0
81.88
1000000.0
121.0
78.9

Contents of 2.txt:

3.497142e+00
5.868075e+00
4.807286e+00
2.236068e+00
5.000000e+00
7.000000e+00
9.048757e+00
1.000000e+03
1.100000e+01
8.882567e+00

VHDL code:

library IEEE;
use IEEE.STD_LOGIC_1164.ALL;
use IEEE.MATH_REAL.ALL;
library std;
use std.textio.all;

entity file_handle is
end file_handle;

architecture Behavioral of file_handle is

type real_array is array(1 to 10) of real;

begin

process

variable line_var : line;
file text_var : text;
variable r : real_array;


begin        

       
   --Open the file in read mode.
   file_open(text_var,"1.txt",read_mode);
    --run the loop 10 times to read 10 real values from the file.
    for i in 1 to 10 loop
    --make sure its not the end of file.
    if(NOT ENDFILE(text_var)) then
     readline(text_var,line_var);   --read the current line.
      --extract the real value from the read line and store it in the variable.
     read(line_var,r(i));
    end if;
    end loop;
    file_close(text_var); --close the file after reading.
 
    --Write the square root values of variable 'r' to another file.
    file_open(text_var,"2.txt",write_mode);
    --run the loop 10 times to write 10 real values to the file.
    for i in 1 to 10 loop
      write(line_var,sqrt(r(i))); --sqrt is a fucntion for finding square root.
        writeline(text_var,line_var);
    end loop;
    file_close(text_var);

  wait;

end process;

end Behavioral;

This way of reading and writing files is very helpful in many situations. In my next post I will show an example based on this code snippet.

3 comments:

  1. Hi!

    Is there a way to read in integers which appear as hexadecimal values inside the file?... I mean using pure textio?

    ReplyDelete
    Replies
    1. this is an excellent question and i'd also like to know the answer :)

      Delete
  2. For above program, I am getting this error : File does not exist.
    Does anybody have solution for this?

    ReplyDelete