I have the following piece of code:
while (fgets(line,1024,file))
{
getchar();
printf(line);
i++;
line = (char*)realloc(line, sizeof(char)*sizes[i]);
}
and for some reason when I printf the line, it prints two lines. How can it be?
full code:
int main()
{
FILE * file = fopen("C:/Users/user/Desktop/a.txt","r");
char c;
int count=0;
int words=0;
int* sizes = (int*)calloc (count+1,sizeof(int));
if (file)
{
do
{
c= getc(file);
words++;
if (c=='\n'|| c==EOF)
{
sizes[count]=words+1;
count++;
words=0;
if (c=='\n')
sizes = (int*)realloc(sizes,(count+1)*sizeof(int));
}
}while (c!=EOF);
rewind(file);
char* line = (char*)malloc(sizeof(char)*(sizes[0]));
int i=0;
while (fgets(line,1024,file))
{
getchar();
printf("%s",line);
i++;
line=(char*)realloc(line,sizeof(char)*sizes[i]);
}
printf(line);
free(line);
/*for (int i=0; i<8; i++)
{
printf("%d\n",sizes[i]);
}*/
free(sizes);
fclose(file);
}
getchar();
return 0;
}
as you see, I count each line's length, put it into array, than allocate a string according to the line's length.