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.
You will have to read all the lines up to the one you want.
I'd probably use
fgets()
to read the lines andsscanf()
to parse the required line. However, you can add a loop to read the unwanted lines (stillfgets()
) and then read the line you want withfscanf()
. Do check that you got three values: you must check the return value fromfscanf()
. Also remember to close the file you opened.Note that this code does not actually enforce lines separating the sets of numbers (one of the disadvantages of the file-based members of the
scanf()
family of functions. For that, you needfgets()
andsscanf()
:you need to use checks for your input scans. you might potentially run into errors or EOF.