You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

SystemVerilog中$fscanf读取CSV文件异常如何修复?

修复SystemVerilog中$fscanf读取CSV时的字段分割问题

在使用SystemVerilog的$fscanf读取CSV文件时,遇到字段分割错误:CSV每行格式为寄存器名+十六进制值(如REG_1,0xab4556),但原代码将整行内容都读入第一个变量,导致第二个变量始终为0。

CSV文件示例:

REG_1,0xab4556
REG_2,0x124d

原错误代码:

while (!$feof(file)) begin
    $fscanf(file, "%s,%x", register_name, expected_value);

    $display("Register Name: %s, Value: %h", register_name, expected_value);
end

错误输出:

Register Name: REG_1,0xab4456, Value: 0x00000000

解决方案

问题根源在于%s格式符会读取所有连续的非空白字符,而逗号不属于空白字符,因此它会把逗号及后续的十六进制值全部纳入第一个变量。

需要修改$fscanf的格式字符串,明确指定以逗号作为字段分隔符:

  • 使用%[^,]匹配逗号之前的所有字符(即寄存器名)
  • 用,%x匹配逗号,然后读取十六进制值

修正后的代码:

while (!$feof(file)) begin
    // %[^,] 读取逗号前的所有字符,跳过逗号后读取十六进制值,末尾\n匹配换行符避免残留干扰
    $fscanf(file, "%[^,],%x\n", register_name, expected_value);

    $display("Register Name: %s, Value: %h", register_name, expected_value);
end

补充说明:

  • 格式末尾的\n用于匹配每行的换行符,避免残留的换行符干扰下一次读取
  • 确保register_name变量的宽度足够容纳最长的寄存器名,避免截断

修正后的输出:

Register Name: REG_1, Value: 0xab4556
Register Name: REG_2, Value: 0x0000124d

内容的提问来源于stack exchange,提问作者Pratheek Motamarri

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.06 18:32:42