Hello all...
Iam Avinash from India.
I wanted to know how to extract a number from a specified line in a text file using C. I know how to read a file but couldn't retrieve the number. Is there any string or numeric conversions to be done upfront.
#include <stdio.h>
int main()
{
// read integer from a specified line in text file
int line_number = 23 ; // first line is line number 1
printf( "try to read integer from line %d of file " __FILE__ "\n", line_number ) ;
FILE* file = fopen( __FILE__, "r" ) ;
int ch ;
while( line_number > 1 && ( ch = fgetc(file) ) != EOF )
if( ch == '\n' ) --line_number ; // skip till we reach the required line
int number ;
int result = fscanf( file, "%d", &number ) ;
if( result != 0 && result != EOF ) printf( "number %d was read\n", number ) ;
}
/*
12345
67
8901
2345
67890
123
*/
But if a single line has more numbers delimited with space, like....
"Strain 0.000234 0.00237 0.00241 0.00089".
How to store these numbers? if we use arrays...size of the array should be defined before. But I dont know how many values are present in the line.
But if a single line has more numbers delimited with space, like....
"Strain 0.000234 0.00237 0.00241 0.00089".
How to store these numbers? if we use arrays...size of the array should be defined before. But I dont know how many values are present in the line.
The code given by JLBorges will still work well to get you to the correct line.
After you get to the correct line, a simple approach could be to use a fixed-size char buffer to read the line into, then a fixed-size double array to read the numbers in, by using strtok() and strtod().
EDIT: Hadn't seen the post by Catfish666 when I wrote this. So this post is redundant.
Leaving it in, just in case a dynamically resized array is really needed.