Think I will be very easy to make fscanf read a file with 2 columns. You just need to change the 'format' (i.e. second input of fscanf) to \f\t\f\n. This would expect a float, a tab, another float and then a new line.
I forgot to mention. I'm having some trouble making this code accept doubles? I have changed it a few things around:
Code:
#include <stdio.h>
int foo(const char *filename, double *array, int size)
{
int count = 0;
FILE *file = fopen(filename, "r");
if ( file )
{
double *end = array + size;
while ( fscanf(file, "%f", array) == 1 )
{
if ( ++array >= end )
{
puts("too many inputs");
break;
}
++count;
}
fclose(file);
}
else
{
perror(filename);
}
return count;
}
int main()
{
double array[10];
int i, count;
count = foo("test1.txt", array, sizeof array / sizeof *array);
for ( i = 0; i < count; ++i )
{
printf("array[%i] = %d\n", (int)i, array[i]);
}
return 0;
}
This builds with out any error, but returns junk! Have a look:
Code:
array[0] = 1065353216
array[1] = 1073741824
array[2] = 1079613850
array[3] = 1085485875
array[4] = 1091148186
array[5] = 1092301619
I have changed size_t because I don't really understand it. But I figure the output of 'foo' will always be an int. Also, the input will always be a double. Can anybody see the problem? (I have of course changed the input file to contain numbers that have a decimal point):
1.0
2.0
3.4
5.6
8.6
9.7
Sorry about this guys but the printf should read
Code:
printf("array[%i] = %f\n", (int)i, array[i]);
This also changes the output as would be expected. However, it's still not what's in the file!