Search code examples
scanfverilogsystem-verilogfgets

Read each character from file and store in array


I need to use Verilog to store each character from input file into an array.

I'm able to use $fgets to read each line, but I'm not sure how to break it down to each character.

Input file:

foo
bar 
joe
stack

main:

c = $fgetc(infile);
while(c != `EOF) begin
  r = ungetc(c,infile);
  $fgets(str,infile);
  c = $fgetc(infile);
  $display (%0s,str);
end

I want to store it into str so that [0]str[0] = f and so on.


Solution

  • You can use $fscanf to read one line at a time, discarding the newline character. Since each line only has one word, store the word into a temporary string variable word. Then push each word into a queue of strings.

    module tb;
    
    int fd;
    string word;
    string str [$];
    
    initial begin
        fd = $fopen("data.txt", "r");
    
        while (! $feof(fd)) begin
            void'($fscanf(fd, "%s\n", word));
            str.push_back(word);
        end
    
        $display("%s", str[0][0]);
        $display("%s", str[0][1]);
        $display("%s", str[0][2]);
    end
    
    endmodule
    

    Prints:

    f
    o
    o