【问题标题】:file read using fgetc adds FF at the end使用 fgetc 读取的文件在末尾添加 FF
【发布时间】:2018-04-25 18:10:48
【问题描述】:

我正在使用 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..

写文件: 0000000: 0000 1567 d48d ff ...g...

谢谢!

【问题讨论】:

    标签: system-verilog fgetc


    【解决方案1】:

    您在写入文件末尾获得额外的'hff 的原因是$feof(或通常foef C 函数)的工作方式。简而言之,它不检查下一次读取是否超出文件末尾,而是检查前一次读取是否超出文件末尾。因此,如果您使用$fgetc 逐个字符(逐个字节)读取,则$feof 只会在$fgetc 读取文件末尾并返回EOF 本身时返回true(即-1 或'hff 如果转换为 logic [7:0])。您应该在每次读取一个字节时检查此错误情况,如下所示:

    integer fd, ch;
    ...
    fd = $fopen("file.bin", "rb");
    ...
    while ((ch = $fgetc(fd)) != -1) begin
      $display(ch);
    end
    

    【讨论】:

    • 我也试过了。我读取了备用字节,显示如下:read_byte is 00000000 read_byte is 00000067 read_byte is 0000008d 如果您看到上述文件中缺少 15 和 d4
    • @coding_gal 您是否在代码中两次调用$fgetc?请注意,我只调用一次来检查EOF 以及在我的示例代码中设置ch。我不在循环体中调用它,只在条件中调用它。如果您仍然遇到问题,您可以通过编辑您的答案发布您正在尝试的导致该结果的代码吗?
    • 哦,是的,我没有注意到。谢谢!很多。
    • @coding_gal 没问题,如果您准备好了,请接受答案,或者如果您需要更多帮助,请告诉我们。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-16
    相关资源
    最近更新 更多