【发布时间】: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. 打开文件
获取当前行
-
scanf 格式化当前行
获取前 8 位数字
将它们保存到数组中
循环到文件末尾(而不是像上面的代码中那样
我是 c 的新手,习惯于 java。
【问题讨论】:
-
为什么“文件不存在?!” ?您可以使用 perror() 获得有用的错误消息。