This program stops executing though compiler compiled successfully. What I try to do here is, read every line of my text file and then copy the line to the array because I want to access to all of them later. Where is the mistake? Thanks in advance.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main ( ){
typedefchar* string; //use "typedef" instead of "char*"
char line[100];
int i, k;
string array[100]; //an array of strings
int num_of_lines;
FILE *file = fopen ( "eng101.txt", "r" );
if ( file != NULL ){
for (i=1 ; fgets ( line, 100,file ) != NULL ;i++ ){ //for every line
array[i]=malloc(100);//allocate space for the string
strcpy(array[i], line); //copy the line as a string to the array's ith element
}
num_of_lines=i;//use this so you can tell how many lines wer in the file
fclose ( file );
}else{
perror ( "eng101.txt" );
}
getchar();
return 0;
}
You could use strdup() instead of malloc() + strcpy()
1 2 3 4
for (i=1 ; fgets ( line, 100, file ) != NULL ;i++ ){ //for every line
array[i]=strdup(line); // allocate a buffer of the required length for
// the string and copy it into it
}
And to be tidy, you should call free() on all strings you allocated.
One more question;
When I declare another variable such as
char line[100], x[100];
or just declare the x below
char x[100],
this program doesn't give any output. What this got to do with it?? I will need much more varaiables