Reading file names from directory with SystemVerilog

Viewed 50

Using SystemVerilog I am trying to see if a file name already exists in my test directory. For example I want to write a file called text_1a2b3c4d.txt but need it to have a unique name. The test will be run multiple times and a random hex number will be used in the file name.

I initially attempted to open the file with the following approach and check to see if a zero would be returned (which is does). The code completes, however, I get an warning when the file is not found, which I would like to avoid in the env I am working in.

module file_write;
   
    int                 file_status = 1;
    bit [31:0]          rand_id;
    string              s_rand_id;
    string              file_name;
  
  initial begin
     
    while (file_status !== 0) begin
        rand_id = $urandom();      // Generate rand 32 bit value
        s_rand_id.hextoa(rand_id); // convert rand 32 bit value to string for file name
        file_name = {"text_", s_rand_id, ".txt"}; // Create filename in format txt_rand#.txt
        file_status = $fopen(file_name, "r");
        if (file_status !==0) $display("Hex ID: %h already used, regenerating", rand_id);
        $fclose(file_status); // Close file descriptor
    end
    
    $display("End of section");
    
  end
endmodule

Is there a way to read all file names in a directory that way I could search for a name match? or are there other recommended ways to approach this? Any help would be appreciated.

1 Answers

Ended up finding a different approach which avoided the error. This involves using $system().

module file_write;
   
    int                 file_status = 1;
    bit [31:0]          rand_id;
    string              s_rand_id;
    string              file_name;
  
    initial begin
    
    while (file_status !== 0) begin
        rand_id = $urandom(); // Generates random 32-bit value
        s_rand_id.hextoa(rand_id);
        file_name = {"text_", s_rand_id, ".txt"}; // Create filename in format text_rand#.txt

        if($system($sformatf("test -f ./folder/%s", file_name)) == 0) begin // File exists
            $display("Hex ID: %h already used, regenerating", rand_id);
        end
        else begin // File does not
             file_status = 0;
        end
    end

    $display("End of section");
    
    end
endmodule

The test -f command returns 0 when the file exists. This method does not propagate any warning/error messages in my environment, which satisfies my requirements.

Related