使用fgetc读取的文件最后添加了FF

问题描述 投票:-1回答:1

我正在使用fgetc读取文件。文件读取以偏移量开始。最后我看到8'hFF附加在文件的末尾。我期待文件中的6个字节但是看到7个字节。我不知道为什么会发生这种情况。有任何想法吗?

以下是我的代码:

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

下面是文件内容(十六进制):input_file的最后一行(总文件大小= 1878):

0000750:0000 1567 d48d ... g ..

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

谢谢!

system-verilog fgetc
1个回答
0
投票

您在书面文件末尾获得额外'hff的原因是由于$feof(或通常是foef C函数)的工作原理。简单地说,它不会检查下一次读取是否在文件末尾,而是先前的读取是否从文件末尾读取。因此,如果你使用$fgetc逐个字符地逐字节地阅读,$feof将仅在$fgetc读取文件末尾时返回true,并返回EOF本身(即,如果转换为'hff,则返回-1或logic [7:0])。每次读取一个字节时都应检查此错误情况,如下所示:

integer fd, ch;
...
fd = $fopen("file.bin", "rb");
...
while ((ch = $fgetc(fd)) != -1) begin
  $display(ch);
end
© www.soinside.com 2019 - 2024. All rights reserved.