-
I/O
how can I read a data file to an array:
Have tried using fread() but doesnt work
Code:
int *fp;
fp=&array;
if ((input=fopen("data.txt","r"))==NULL)
{
error msg;
}
fseek(input,0L,SEEK_END);
lFileLen=ftell(input);
rewind(input);
fread(fp, lFileLen,1,input);
-
It could be that your file isn't the same size as your array...
Try
Code:
int done;
done = fread(fp, sizeof(array),1,input);
The done variable should equal 1 after the fread if successful, because it is reading 1 array 'block'.
Of course, this will only work if you have outputted the whole array to the file using fwrite.
-
> if ((input=fopen("data.txt","r"))==NULL)
When you load data.txt file into your editor, do you see
- a mess of hexadecimal bytes and lots of \0 ?
In which case fread is appropriate.
- a nice easy to read file containing say
1 2 3 4
10 20
30 40
In which case you should be using fgets + sscanf (or fgets + strtol).
-
got it working
thanks all
worked it out;
Code:
int main()
{
FILE *file;
char string[50000];
char *array[50000];
int i,j;
file = fopen("data.txt","r");
if(file==NULL)
perror("Error opening file");
else{
fgets(string,50000,file);
}
array[0]=strtok(string, " \n\t");
for(i=1;i<50000;i++){
array[i]=strtok(NULL, " \n\t");
if(array[i]==NULL)
break;
}
for(j=0;j<50000;j++)
{
if(array[j]==NULL)
break;
printf("%s\n",array[j];
}
fclose(file);
return 0;
}
-
Since you're breaking out of the loop at the first occurrence of NULL, you might as well have stopped doing the strtok() at that point too... saving a lot of work. Instead of blindly going for a full 50000.