newbie: need help using malloc in a loop
Hi all. :)
Here are my objectives:
1. Redirect a list of files in a directory into a text file.
2. Open the text file for reading.
3. Put each line of the file into an array of pointers, as strings.
4. Print the array of pointers(strings).
I need to allocate memory to an array of pointers, but I can't get the logic(sequence) right. The program compiles, but crashes.
Code:
#include <stdlib.h>
#include <stdio.h>
#define NUMBEROFFILES 1500
#define FILENAMESIZE 40
int main( void )
{
/* Array of pointers to store filenames */
char *files[NUMBEROFFILES];
int counter;
FILE *openfile;
char *string;
/* Get a list of files in the directory "testwebsite", and redirect the
output to a file called "directorylisting.txt". */
system("dir c:\\testwebsite\\*.html > directorylisting.txt");
/* Test to see that the file "directorylisting.txt" can be opened for reading. */
if( (openfile = fopen("directorylisting.txt", "rt")) == NULL)
{
perror("\ndirectorylisting.txt");
exit( EXIT_FAILURE );
}
counter = 0;
while( fgets(files[counter], BUFSIZ, openfile) != NULL)
{
files[counter] = (char *)malloc( BUFSIZ * sizeof(char)); /* Try to allocate memory for string */
if( files[counter] == NULL )
{
perror("\nMemory allocation error");
exit( EXIT_FAILURE );
}
counter++;
}
fclose(openfile);
/* Print the strings in the array of pointers */
for( counter = 0; counter < NUMBEROFFILES; counter++)
printf("\nFilename %d: %s", counter, files[counter]);
return 0;
}
I know I am allocating the memory after it is needed, not before, but I just can't seem to achieve it. Do I need use a for() loop nested within the while() loop, or vice versa?
I've also tried:
Code:
while( (fgets(files[counter], BUFSIZ, openfile) != NULL) && (files[counter] = (char *)malloc( BUFSIZ * sizeof(char) != NULL )))
but it also crashes, even though it compiles.
This is a failure of logic, and I've got a big headache trying to figure it out. Any help would be appreciated.
Thanks in advance. :)