使用的fscanf从给定的行读取 [英] Use fscanf to read from given line
问题描述
我想读到有多达10行的txt文件。该文件的格式是这样上的所有行:
1 1 8
2 2 3
3 1 15
4 2 7
我想写将从只传递给它一个int提供的线上阅读功能。我想用一个for循环线路不扫描任何重复,但我无法弄清楚如何实现这一点。
我的功能,至今看起来像这样,for循环尚未实现正常呢。
无效过程(INT LINENUM,字符*全名)
{
INT二,NUM1,NUM2,NUM3; FILE * F;
F = FOPEN(全名,R); 如果(F == NULL)
{
的printf(错误:无法打开%S,全名);
} 其他
{
用于(ⅱ= 0(ⅱ= 0;ⅱ≤(LINENUM-1);ⅱ++)
{
/ *通过无扫描线移动* /
的fscanf(F,%D%D,&安培; NUM1,&安培; NUM2,&安培; NUM3);
} 的printf(数字是:%D%d个\\ N,NUM1,NUM2,NUM3);
}
}
您差不多快完成,但你只需要更改格式specifier.The以下code通过线$ P $读取pceding您的预期线,但忽略它的读取。
为(ⅱ= 0(ⅱ= 1;ⅱ≤(LINENUM-1);ⅱ++)
{
/ *通过无扫描线移动* /
的fscanf(F,%* D%* D%* D%* C);
//的fscanf(F,%* D%* D%* D \\ n);
}
的fscanf(F,%D%D,&安培; NUM1,&安培; NUM2,&安培; NUM3);
I want read a txt file that has up to 10 lines. The file is formatted like this on all lines:
1 1 8
2 2 3
3 1 15
4 2 7
I'm trying to write a function that will read from only the line provided by an int passed to it. I thought of using a for loop to iterate through the lines without scanning anything but I can't figure out how to implement that.
My function so far looks like this, the for loop has not been implemented properly yet.
void process(int lineNum, char *fullName)
{
int ii, num1, num2, num3;
FILE* f;
f = fopen(fullName, "r");
if(f==NULL)
{
printf("Error: could not open %S", fullName);
}
else
{
for (ii=0 (ii = 0; ii < (lineNum-1); ii++)
{
/*move through lines without scanning*/
fscanf(f, "%d %d %d", &num1, &num2, &num3);
}
printf("Numbers are: %d %d %d \n",num1, num2, num3);
}
}
You were nearly done but you simply need to change the format specifier.The following code reads through the lines preceding your intended line,but ignores what it reads.
for (ii=0 (ii = 1; ii < (lineNum-1); ii++)
{
/*move through lines without scanning*/
fscanf(f, "%*d %*d %*d%*c");
// fscanf(f, "%*d %*d %*d\n");
}
fscanf(f,"%d%d%d",&num1,&num2,&num3);
这篇关于使用的fscanf从给定的行读取的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!