How to read from a specific line from a text file

2019-01-28 12:03发布

问题:

I am doing a program in VHDL to read and write data. My program has to read data from a line, process it, and then save the new value in the old position. My code is somewhat like:

WRITE_FILE: process (CLK)
variable VEC_LINE : line;
file VEC_FILE : text is out "results";
 begin

if CLK='0' then
write (VEC_LINE, OUT_DATA);
writeline (VEC_FILE, VEC_LINE);
end if;
end process WRITE_FILE;

If I want to read line 15, how can I specify that? Then I want to clear line 15 and have to write a new data there. The LINE is of access type, will it accept integer values?

回答1:

Russell's answer - using two files - is the answer.

There isn't a good way to find the 15th line (seek) but for VHDL's purpose, reading and discarding the first 14 lines is perfectly adequate. Just wrap it in a procedure named "seek" and carry on!

If you're on the 17th line already, you can't seek backwards, or rewind to the beginning. What you can do is flush the output file (save the open line, copy the rest of the input file to it, close both files and reopen them. Naturally, this requires VHDL-93 not VHDL-87 syntax for file operations). Just wrap that in a procedure called "rewind", and carry on!

Keep track of the current line number, and now you can seek to line 15, wherever you are.

It's not pretty and it's not fast, but it'll work just fine. And that's good enough for VHDL's purposes.

In other words you can write a text editor in VHDL if you must, (ignoring the problem of interactive input, though reading stdin should work) but there are much better languages for the job. One of them even looks a lot like an object-oriented VHDL...



回答2:

Use 2 files, an input file and an output file.

file_open(vectors, "stimulus/input_vectors.txt", read_mode);
file_open(results, "stimulus/output_results.txt", write_mode);

while not endfile(vectors) loop
   readline(vectors, iline);
   read(iline, a_in);
   etc for all your input data...

   write(oline, <output data>
end loop;

file_close(vectors);
file_close(results);