1
votes

I tried write binary file in SystemVerilog in my testbench.

int file   = $fopen(path,"w");
if (!file) begin
    $error("File could not be open: ", path);
    return;
end
$fwrite(file, "%u", 32'h4D424D42);
$fclose(file);

And get result: 02 0c 02 0c

I use QuestaSum 10.2c. Why i get this result? Thanks.

1
When I use %h, then data print into file as text: "4D424D42". I tried cast 4-state data type into 2-state before call $fwrite data type and get correct result: int tmp = int'(32'h4D424D42); $fwrite(file, "%u", tmp); - Андрей Кущенко
@MaximG %h won't output a binary file; it outputs an ASCII file. - Matthew Taylor

1 Answers

3
votes

%u puts raw unformatted binary data into the file. Do not expected it to be in readable format. Ensure that you are opening the file in binary format "rb" or "wb" ... .Try reading back the binary data and that should show the written value.

You can use %z if you want to save 4 state values.

int rd;
int file   = $fopen(path,"wb"); // open in binary mode
if (!file) begin
    $error("File could not be open: ", path);
    return;
end
$fwrite(file, "%u", 32'h4D424D42);
$fclose(file);
 // read back binary data from file 
file = $fopen (path,"rb");  // open in binary mode
if (!file) begin
    $error("File could not be open: ", path);
    return;
end
$fscanf(file,"%u",rd);
$fclose(file);
$display("%h",rd);