c中的文件处理:无法正确读取表格式数据
但我不能得到正确的值与破表如下…我如何才能解决它?(在这里,它应该在没有找到任何值的情况下工作,它应该返回“null space”或零..但不是下一个值..) 以及 data.txtc中的文件处理:无法正确读取表格式数据,c,file-handling,C,File Handling,但我不能得到正确的值与破表如下…我如何才能解决它?(在这里,它应该在没有找到任何值的情况下工作,它应该返回“null space”或零..但不是下一个值..) 以及 data.txt data.txt 1 34 2 3 45 4 5 67 上面是我从文件中读取表格的c代码。其中..最后一个值打印了2次 #include <stdio.h> int main(void) { clrscr(); FILE *fin; fin=fopen("d
data.txt
1 34
2
3 45
4
5 67
上面是我从文件中读取表格的c代码。其中..最后一个值打印了2次
#include <stdio.h>
int main(void)
{
clrscr();
FILE *fin;
fin=fopen("data.txt","r");
if(fin==NULL)
{
printf("can not open input fil");
return 0;
}
long data[2];
while(!feof(fin))
{
fscanf(fin,"%ld %ld",&data[0],&data[1]);
printf("\n%ld %ld",data[0],data[1]);
}
fclose(fin);
return;
}
由于文件读取循环的结构,最后一个值将打印两次。只有尝试读取超过文件末尾的内容时,才会设置eof()
标志。当fscanf()
从文件的最后一行eof()
读取最后两个long
s时,尚未设置,但下一次调用fscanf()
失败并设置eof()
,但不会立即查询fscanf()
的结果,使用之前提取的long
s:立即检查所有读取操作的结果
一种可能的解决方案是一次读取一行,使用,然后使用从读取的行中提取
long
值。如果使用了fscanf()
,它将读取新行字符以定位第二个请求的long
,这不是所需的行为
例如:
1 34
57
3 45
4
5 34
(在回答问题更新时)要区分缺少第二个值的行: 二, 和缺少第一个值的行: 57 需要有效的范围(或某些其他标准)来确定行中缺少的值(第一个或第二个):
char line[1024];
while (fgets(line, 1024, fin))
{
/* Assign appropriate default values.
sscanf() does not modify its arguments
for which it has no value to assign.
So if 'line' has a single long value
data[1] will be zero. */
long data[2] = { 0, 0 };
/* You can use 'result' if you require to take particular
action if it reads only 1, or 0, items. */
int result = sscanf(line, "%ld %ld", &data[0], &data[1]);
printf("\n%ld %ld",data[0],data[1]);
}
int result=sscanf(行,“%ld%ld”、&data[0]、&data[1]);
如果(1==结果)
{
如果(数据[0]>=1&&data[0]
feof
在您尝试读取文件末尾之前不会返回true
,因此循环将频繁执行一次。最好检查fscanf
的返回值,如果它与您期望的值不匹配(本例中为2),则检查EOF。以下是一种可能的重构:
while(!feof(fin))
{
fscanf(fin,"%ld %ld",&data[0],&data[1]);
printf("\n%ld %ld",data[0],data[1]);
}
输出类似于…1 34 2 34 3 45 4 45 5 67,在第二种情况下:1 34 57 34 3 45 4 45 5 67(奇数是第一列,偶数是第二列)仍然面临“第一列”的问题缺少值…它将第二个值作为第一个值..并将0指定给第二个值..并且因为它只是示例表…在实际的一个表中,数据大约为5-7000行,可能是列数也增加了。该代码更新(用于检查缺少的第一个值)错误。sscanf
将跳过任何空格。您需要检查行本身的字符:if(行[0]>='1'&&line[0]@paddy,如果第二个值存在,则没有前导空格。检查第一个字符是否为空格根本没有任何帮助。当第一个值丢失时,示例断开文件包含前导空格。我看不出有其他说法。
int result = sscanf(line, "%ld %ld", &data[0], &data[1]);
if (1 == result)
{
if (data[0] >= 1 && data[0] <= 9)
{
printf("\n%ld 0", data[0]);
}
else
{
/* Read value was the second value. */
printf("\n%ld %ld", ++last_first_value, data[0]);
}
}
while(!feof(fin))
{
fscanf(fin,"%ld %ld",&data[0],&data[1]);
printf("\n%ld %ld",data[0],data[1]);
}
int good = 1;
while (good)
{
int itemsRead = fscanf(fin, "%ld %ld", &data[0], &data[1]);
if (itemsRead == 2)
{
// process data[0] and data[1] normally
}
else
{
good = !good;
if (feof(fin))
printf("Hit end of file\n");
else if (ferror(fin))
printf("Error during read\n");
else
printf("Malformed input line\n");
}
}