Monday, May 24, 2010

Coding to read a file from disk in C.?

i need help reagarding coding in C.


I want to read a file from disk ...


that has X rows and Y coloumns...


with numbers in it as data...


and store those numbers into an array using C.





Very urgent ...

Coding to read a file from disk in C.?
Note: "bytekhan" forgot fclose(f); at the end.
Reply:assuming you have an ascii file (as opposed to a binary file) and lets say its a 4x4, you could do the following (if I remember correctly):





#include %26lt;stdio.h%26gt;





#define Xsize 4


#define Ysize 4


void main() {


FILE *f


int M[Xsize][Ysize];


int x;


int y;





f = fopen("my_data_file", "r");





for (x = 0; x %26lt;Xsize; x++) {


for (y = 0; y %26lt;Ysize; y++) {


fscanf("%d", %26amp;M[x][y]);


}


}


}





Or something like this but I think you get the picture. If you don't know the exact size (rows and columns), you'll have to do some dynamic memory allocation using malloc().


No comments:

Post a Comment