I have written this code and i don't know why it has the following two problems:
1)It copys strings from the text file in to the Odd parts of the Array (ex:lines[3] or lines[5] )
2)It doesn't copy all the file but stops whenever it wants and crashes in the end.
Please help me with this and if someone can tell me how to copy a specific string from an text file in C it would be much appreciated !
C CODE :
#include <stdio.h>
int height, length;
int main()
{
int i;
char **lines;
FILE *tfile = fopen("this.txt", "r");
if (tfile != NULL )
{
fscanf(tfile, "%d %d", &height, &length);
printf("here:%d,%d\n", height, length);
/*dynamic equasition of memory with malloc*/
lines = (char **) malloc(sizeof(char *) * (height + 1));/*height + 1 ('\0')*/
for (i = 0; i < 2 * height; i++)
{
lines[i] = (char *) malloc(sizeof(char) * (length + length + 1));/*height + height ('|') + 1 ('\0')*/
}
for (i = 0; i < (2 * height); i++)
{
fgets(lines[i], ((2 * length) + 1 + 1), tfile);/*length='spaces' + length+1='|' + 1='\0'*/
if (i % 2 != 0)
{
printf("%s\n", lines[i]);
}
}
fclose(tfile);
}
else
{
printf("Error: unable to open file.");
}
free(lines);
return 0;
}
TEXT FILE (this.txt) :
http://www.csd.uoc.gr/~hy100/glid.txt
Every answer is much appreciated. IT