I am trying to read a file which contains the coordinate values for my code.
My question is, how do I make the array size large enough to contain future addition to the file?
Below is my code; when I set the array to size 905, my loop continues until the space is filled. Why is that?
FILE.txt:
S (60,70)(200,200)
S (30,40)(100,200)
S (10,20)(80,10)
S (60,400)(700,200)
S (160,70)(240,20)
S (160,70)(240,20)
S (160,70)(240,20)
My code:
#include <stdio.h>
int a;
int b;
int c;
int d;
int data[905][4];
int main ( int argc, char *argv[] )
{
if ( argc != 2 ) /* argc should be 2 for correct execution */
{
/* We print argv[0] assuming it is the program name */
printf( "usage: %s filename", argv[0] );
}
else
{
// We assume argv[1] is a filename to open
FILE *file = fopen( argv[1], "r" );
/* fopen returns 0, the NULL pointer, on failure */
if ( file == 0 )
{
printf( "Could not open file\n" );
}
else
{
int j=0;int count=1
for (j=0; j < count; j++)
{
fscanf(file, "S (%d,%d)(%d,%d)", &a, &b, &c, &d);
printf("%d,%d,%d,%d\n",a, b, c, d);
count++
}
fclose( file );
}
}
}
You will need to use the
mallocandreallocfunctions from<stdlib.h>for this. The basic idea is to allocate a certain amount of space up front, and then enlarge the array when you discover that it is not big enough.It will make life easier if you use an array of structures rather than an array of arrays:
and then you do something like this:
Obligatory tangential comment: Forget you ever heard of
fscanf. It is far more trouble than it is worth. Read entire lines withgetline(if you don’t have it, it’s not hard to implement), extract individual number-strings from the line with a hand-coded parser, and convert them to machine integers withstrtol,strtoul, orstrtodas appropriate.