Showing posts with label Reading and Writing binary files in Systemverilog. Show all posts
Showing posts with label Reading and Writing binary files in Systemverilog. Show all posts

Saturday, February 5, 2022

Reading and Writing Binary files in Systemverilog

Reading a binary file in SystemVerilog might be required occasionally. I have tried to capture some basic information as a guide for someone starting out. 

Comments are embedded in the code: 

function void read_binary_file();
int fread;
bit [7:0] rdata;
int unsigned line_count;
line_count=0;
//Open file with binary read mode("rb"), b here specifies binary
fread=$fopen("binary_file.bin","rb");
if(fread==0)
`uvm_error("NO_FILE_FOUND","Couldn't open file binary_file.bin for reading")
//read until end of file is reached
while(!$feof(fread)) begin
//fgets reads one line at once and $fgetc reads a byte (a character) at once
$fgets(rdata,fread);
line_count+=1;
//Do what's required of data here
`uvm_info(get_name(),$sformatf("byte number %0d, Value= %08x",line_count,rdata),UVM_MEDIUM)
end
//close the opened binary file
$fclose(fread)
endfunction

Similarly an example for writing a binary file
function void writing_binary_file(int unsigned total_bytes_to_write=32);
int fwrite;
bit [7:0] wdata;
//Open file with binary write mode("wb"), b here specifies binary
fwrite=$fopen("binary_file.bin","wb");
if(fwrite==0)
`uvm_error("NO_FILE_FOUND","Couldn't open file binary_file.bin for writing")
//iterate until all intended bytes are written
for(int i=0,i<total_bytes_to_write,i++) begin
//generate current random byte to write
wdata=$urandom_range(0,255);
//fwrite with %c writes only 1 byte at a time, use "%u" format for writing 32bit data
$fwrite(fwrite,"%c",wdata);//Note that fwrite doesn't introduce newline character unless added with \n
end
//close the file
$fclose(fwrite)
endfunction