-1

Possible Duplicate:
reading a text file into an array in c

I'm struggling with reading a text file line by line into lines of an array. I am NOT allowed to use malloc or related commands. The latest code I found is this, which doesn't work:

void readfile(const char *filename) {
FILE *f;
f = fopen(filename, "r");
int linecount;
char inputError;
char a[500];
char array[50];
//struct cal_event one[200];

linecount = 0;
while(inputError != EOF) {
    inputError = fscanf(f, "%s\n", array);
    linecount++;
}
fclose(f);
char names[linecount][500];

f = fopen(filename, "r");
int i;
for(i = 1; i < linecount; i++)
    fscanf(f, "%s", names[i]);
    printf("%s ", names[i]);
fclose(f);
}

I need a code example please! Thanks so much!

Community
  • 1
  • 1

1 Answers1

1
while(inputError != EOF) {
    inputError = fscanf(f, "%s\n", array);
    linecount++;
}

Your 'destination' pointer for fscanf is the same for every loop iteration. This means that each iteration will write the data to the same location, overwriting the previous contents. You need to keep track of the end of the buffer's contents, and use a pointer to the end of the buffer as the 'destination' pointer.

Keeping track of the end of the buffer's contents means that you can do another very important thing: ensure that you don't overflow your array. Since your array is hard-coded to 50 characters, you must ensure that you read no more than 50 characters (total) into it. Otherwise, you'll corrupt memory and all sorts of bad things can happen.

Based on your title, it seems like you want to read the file into an array such that each array element is a string (representing a line of text). Since a string is itself an array, you will want your array object to be an array of arrays. You can also call this a two-dimensional array. For example:

char array[50][100];

This would create an array capable of holding 50 lines of text, where each line can be up to 100 characters long. You would then read the first line into array[0], the next line into array[1], etc etc.

bta
  • 43,959
  • 6
  • 69
  • 99