How to tell if a file opened with $fopen("file.txt", "a") is empty

Status
Not open for further replies.

BartlebyScrivener

Member level 5
Joined
Feb 8, 2012
Messages
90
Helped
0
Reputation
0
Reaction score
0
Trophy points
1,286
Visit site
Activity points
2,081
How to tell if a file opened with $fopen("file.txt", "a") is empty

I am outputting my test results to a text file. If it is the first time the tests have been run, I want to add a line, say including the date, to the text file. If it is not the first time the test has been run, then the text file will all ready have info, and I do not want to add this line.


I tried


Code Verilog - [expand]
1
2
3
4
5
filetxt = $fopen("file.txt", "a")
 
if ($feof(filetxt)) begin
  // date text
end



but that didn't work.

Thanks.
 

Re: How to tell if a file opened with $fopen("file.txt", "a") is empty

I'm not aware of $feof() as a valid Verilog file function. You may try $ftell().
 

Re: How to tell if a file opened with $fopen("file.txt", "a&quot is empty

Thanks, I tried that, but ftell always appears to return 0.


Code Verilog - [expand]
1
2
3
4
5
6
7
8
9
10
11
initial begin
    file = $fopen("file.txt", "a");
    pos  = $ftell(file);
    if(pos == 0) begin
      $fdisplay(file, "First line 1 %g", pos);
      $display("wrote first line, $ftell(file) returned %g ", pos);
    end else begin
      $fdisplay(file, "Subsequent lines %g ", pos);
      $display("wrote a subsequent, $ftell(file) returned %g ", pos);      
    end
  end



- - - Updated - - -

I have got it working by using file = $fopen("file.txt", "r"); If it fails and gives an error, then I open it using "a" and add the first line. If it passes, then I close it and open it with "a" and add subsequent lines. Seems a little crude though.
 

Re: How to tell if a file opened with $fopen("file.txt", "a") is empty

Do you see $ftell() reflecting a file position at all? Did you try an explicite position to EOF?
Code:
$fseek(file, 0, 2);
 

Status
Not open for further replies.
Cookies are required to use this site. You must accept them to continue using the site. Learn more…