-1

I'm reading a file using fgetc. File reading starts at an offset.At the end I see 8'hFF getting appended at the end of file.I'm expecting 6 bytes in the file but see 7 in them.I'm not sure why this is happening. Any ideas?

Below is my code:

module file_read();
   integer fd,fd1,file_char,status;
   logic [7:0] captured_data;

   initial begin
        fd = $fopen("input_file", "rb");
        fd1 =$fopen("write_file","w");
        status=$fseek(fd,1872,0);

        assert (status);
      //  while ($fgetc(fd) != `EOF) begin
          while (!$feof(fd)) begin
          file_char=$fgetc(fd);
          $display("file char is %h",file_char);
         end
   end // initial begin

Below are the file contents(in hex): last line of input_file(total file size =1878):

0000750: 0000 1567 d48d ...g..

write_file: 0000000: 0000 1567 d48d ff ...g...

Thanks!

1 Answers1

1

The reason you are getting the extra 'hff at the end of the written file is due to how $feof (or generally the foef C function) works. Simply put, it doesn't check if the next read is off the end of the file but if the previous read read off the end of the file. So, if you are reading character by character (byte by byte) using $fgetc, $feof will only return true once $fgetc reads off the end of the file, and returns EOF itself (ie, -1 or 'hff if converted to logic [7:0]). You should be checking for this error condition each time you read a byte, something like this:

integer fd, ch;
...
fd = $fopen("file.bin", "rb");
...
while ((ch = $fgetc(fd)) != -1) begin
  $display(ch);
end
Unn
  • 4,775
  • 18
  • 30
  • I have tried that too.I read alternate byte, display looks like this :read_byte is 00000000 read_byte is 00000067 read_byte is 0000008d If you see 15 and d4 are missing from the above file – coding_gal Apr 25 '18 at 21:53
  • @coding_gal Are you calling `$fgetc` twice in your code? Notice I only call it once both to check for `EOF` as well as set `ch` in my example code. I do not call it in the body of the loop, only in the conditional. If you are still having an issue, can you post the code you are trying that is leading to that result by editing your answer? – Unn Apr 25 '18 at 22:08
  • Ohh yeah I did not notice that.Thanks! a lot. – coding_gal Apr 25 '18 at 22:28
  • @coding_gal No problem, accept the answer if youre set or let us know if you need more help. – Unn Apr 25 '18 at 22:36