【问题标题】:C - Fgets &Scanf to read from a text fileC - Fgets &Scanf 从文本文件中读取
【发布时间】:2012-02-10 17:34:06
【问题描述】:
#include <stdio.h>

int main() {
FILE *f;
unsigned int num[80];
int i=0;
int rv;
int num_values;

f=fopen("values.txt","r");
if (f==NULL){
    printf("file doesnt exist?!\n");
    return 1;
}

while (i < 80) {
    rv = fscanf(f, "%x", &num[i]);

    if (rv != 1)
        break;

    i++;
}
fclose(f);
num_values = i;

if (i >= 80)
{
    printf("Warning: Stopped reading input due to input too long.\n");
}
else if (rv != EOF)
{
    printf("Warning: Stopped reading input due to bad value.\n");
}
else
{
    printf("Reached end of input.\n");
}

printf("Successfully read %d values:\n", num_values);
for (i = 0; i < num_values; i++)
{
    printf("\t%x\n", num[i]);
}

return 0

}

从另一个问题中得到了上面的代码,但是有问题对其进行编辑以满足我的要求,每次我更改它似乎到处都是错误。

这也只是一个简单的改变。

来自文件的示例输入是 12345678

87654321

1234567811

12345678

当使用此方法从文件中读取时,我只希望它获取前 8 个十六进制数字并保存它们。

我尝试使用 fgets 获取该行,然后使用 scanf 对其进行格式化,但错误失控了。

我脑海中的想法但不确定如何实施 1. 打开文件

  1. 获取当前行

  2. scanf 格式化当前行

    • 获取前 8 位数字

    • 将它们保存到数组中

  3. 循环到文件末尾(而不是像上面的代码中那样

我是 c 的新手,习惯于 java。

【问题讨论】:

  • 为什么“文件不存在?!” ?您可以使用 perror() 获得有用的错误消息。

标签: c file format scanf fgets


【解决方案1】:

试试

char buffer[201];
while (fgets(buffer, 200, f) != NULL)
{
  if (strlen(buffer) > 7)
  {
     buffer[8] = 0;
     sscanf(buffer, "%x", &num[i++]);
  }
  else
  {
     /* report that the line is error ?! */
  }
}

【讨论】:

  • 这很好,无论如何 fgets 可能在 while() 内,所以它在没有更多行而不是单独的 if 语句时终止?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-09-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-12-22
  • 2019-05-29
相关资源
最近更新 更多