I'm try to create array of strings from a text file. I need a review from experienced programmers about my program. (MinGW gcc, Win7)
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
main()
{
FILE *file;
char *fname = "lines.txt";
file = fopen(fname, "r");
if(file == NULL)
printf("Can't read %s", fname);
char cbuff;
int nlines = 0; //counter of new lines
int chr = 0; //counter of chars (except new line char)
int maxlen = 0;
while( (cbuff = fgetc(file) - 0) != EOF )
{
if(cbuff == '\n')
{
if (chr > maxlen)
{
maxlen = chr + 1;
}
chr = 0;
nlines++;
}
else
{
chr++;
}
}
printf( "lines: %d\nmax string len: %d\n\n", nlines, maxlen );
rewind(file);
char *list[nlines];
int buffsize = maxlen * sizeof(char);
char buff[buffsize];
int i = 0;
while(fgets(buff, buffsize, file))
{
list[i] = malloc(strlen(buff) * sizeof(char));
strcpy(list[i], buff);
i++;
}
fclose(file);
int c = 0;
for(c; c < nlines; c++)
{
printf( "%s", list[c] );
}
}//main
I'm trying to control size of array and items in array. Maybe I have errors somewhere, do not judge strictly.