10.24 2018-11-05 03:23 采纳率: 0%
浏览 276
已采纳

sscanf() skipping delimiter & width

I am writing an assembler for 6502 and trying to read the instructions and opcode data from a file I prepared. Using sscanf to store data and it only worked partially...

File:

ADC,Im,69,2    
ADC,ZP,65,2
ADC,ZPx,75,2
ADC,Ab,6D,3
ADC,Abx,7D,3
ADC,Aby,79,3
...

Here is only part of the code related to the problem. fgets works fine. Problem line commented below. Will upload more if needed.

Code:

  FILE *fp = ...
  char bf[15];
  char name[3];
  char mode[3];
  char op[2];
  int bytes;

  while (fgets(bf,15,fp)) {
    //below is the problem line
    sscanf(bf, "%3[^,],%3[^,],%2[^,],%d", name, mode, op, &bytes);
  }
  printf("%s,%s,%s,%d\n", name, mode, op, bytes);

Output:

ADCIm,Im,69,2
ADCZP,ZP,65,2
ADCZPx75,ZPx75,75,2
ADCAb,Ab,6D,3
ADCAbx7D,Abx7D,7D,3
...

Expected to be (just like the file format):

ADC,Im,69,2
ADC,ZP,65,2
ADC,ZPx75,75,2
ADC,Ab,6D,3
ADC,Abx7D,7D,3
...

It seems that op and bytes all work alright, but there are something wrong with the name and mode variables, even though I contained the width and delimiter in the argument.

转载于:https://stackoverflow.com/questions/53147902/sscanf-skipping-delimiter-width

  • 写回答

1条回答 默认 最新

  • YaoRaoLov 2018-11-05 03:33
    关注

    Actually, it's not sscanf that is at fault. You have undefined behavior due to buffer overruns -- printf knows nothing about the fact that your strings are not null-terminated, and it will continue printing characters until it finds a '\0'.

    To stop it from doing that, you can supply a maximum field width in the format specifier:

    printf("%.3s,%.3s,%.2s,%d\n", name, mode, op, bytes);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥15 stable diffusion
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误