Computing.Net > Forums > Programming > Reading in txt file to an array

Computer Problems? Computing.Net has over 1,000,000 posts about all things technology related! Click here to start participating now! Also, check out the New User Guide.

Reading in txt file to an array

Reply to Message Icon

Name: Jay
Date: October 12, 2002 at 22:35:22 Pacific
OS: Unix
CPU/Ram: 900/256
Comment:

Hello All,

I am doing an game of life program in C lang. I'm stuck on how to read in values from a given file into a 2d array. I'm also having trouble on displaying the array in an interal of 5 until I reach a certain generation. I know I have to use a for loop. Please help soon :-)



Sponsored Link
Ads by Google

Response Number 1
Name: Readfile_into_twodar
Date: October 13, 2002 at 06:09:24 Pacific
Reply:

void print_el(char *s, char *fmt);
char *ptr = NULL;
char *farray[500][50];

int main(int argc, char *argv[]) {
FILE *fpt;
int i = 0,j = 0;

/* start init */
ptr = malloc(256);
fpt = fopen(argv[1],"r");
/* end init */

if (fpt && ptr) {
while ( (fgets(ptr,256,fpt)) != NULL) {
i = j > 49 ? i + 1 : i;
j = j > 49 ? 0 : j + 1;
printf("%d %d: ", i, j);
farray[i][j] = ptr;
print_el(farray[i][j],"Array element: %s\n");
free(farray[i][j]);
ptr = malloc(256);
}
fclose(fpt);
return 0;
} else {
perror("Init");
return 1;
}
return 1;
}

void print_el(char *s, char *fmt) {
printf(fmt, s);
}

How you want to split up your strings,
to arrange for key::value pairs between % 5 countsallocate memory, clean up,etc.. all depends on you. This is a quick and very dirty read and storage and print and free
example.


0
Reply to Message Icon

Related Posts

See More


VB String Manipulation c++ constant declaration



Post Locked

This post is quite old and has been locked from receiving new replies. Please create a new posting instead.


Go to Programming Forum Home


Sponsored links

Ads by Google


Results for: Reading in txt file to an array

reading in a file in java www.computing.net/answers/programming/reading-in-a-file-in-java/7233.html

searching a txt file from an array- www.computing.net/answers/programming/searching-a-txt-file-from-an-array/12047.html

Read a txt file to a variable www.computing.net/answers/programming/read-a-txt-file-to-a-variable/16422.html