File Read

Guys,


module astar ();

int file,c,n,m,i;
string filename;
int      q[$];

initial
begin
    //Get the file name
    if($value$plusargs("filename=%s", filename));
    else filename = "tmp.txt";
    
    // Read file a char at a time
    file = $fopen(filename,"r");
    while (!$feof(file)) begin
        c = $fgetc(file);
        if (c != " " && c != "\n") begin
            q.push_back(c);
            $display(" %0dth Char is = %s ",i++,c);
        end
    end

    foreach (q[i]) $display ("q[%0d] = %s",i,q[i]);

//Get nodes from file
 n = q.pop_front() ;
 m = q.pop_front() ;
 $display(" Maze Dimensions are %0d X %0d ",n,m);

end
endmodule

I’m getting right value from the file, but when I pop from queue and assign to local variable, getting some weird value.

Results:

0th Char is = 3
1th Char is = 5

q[0] = 3
q[1] = 5

Maze Dimensions are 51 X 53

why is that? I don’t understand.

can anyone clarify?

John

When you are reading the values, you are reading them as characters and displaying them as characters as well. When you pop them, you are displaying their decimal values.

For ASCII characters, “3” is hex 0x33 and decimal 51. “5” is hex 0x35 and decimal 53, which corresponds to how you are displaying the Maze dimensions.

In reply to cgales:

How can I get as a value from the file? In my file, some of them are values and others are characters.

Kindly help.

John

In reply to John Verif:

From the LRM:

6.16.9 Atoi(), atohex(), atooct(), atobin()
function integer atoi();
function integer atohex();
function integer atooct();
function integer atobin();
— str.atoi() returns the integer corresponding to the ASCII decimal representation in str. For
example:
str = “123”;
int i = str.atoi(); // assigns 123 to i.

In reply to shalom:

i tried as below…


//Get nodes from file
 s = q.pop_front();
 n = s.atoi();
 s = q.pop_front();
 m = s.atoi();
 $display(" Maze Dimensions are %0d X %0d ",n,m);

Worked for me.

Maze Dimensions are 3 X 5

Thanks.
John

In reply to John Verif:

On more small issue…

If I pass more than 1 digit number, it considered as more than one characters.

How can I get whole number from the file, instead of char?

let say

25
50
_ _ X _
_ S _ X
X _ G X

Note: same file has characters too.

John

In reply to John Verif:

You would be better off using $fscanf to read the file. It would will take care of all the conversions for you.

In reply to dave_59:

Thanks Dave.

It works.


    // Read file a char at a time
    file = $fopen(filename,"r");
    while (!$feof(file)) begin
        code = $fscanf(file,"%s",c);
            q.push_back(c);
            $display(" %0dth Char is = %s ",i++,c);
    end

John