Text reading problem

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#include <stdio.h>
#include <iostream>
#include <string.h>

using namespace std;
int main (  )
{
   typedef char* string;  //use "typedef" instead of "char*"
   char line[100]; 
   int i, k; 
   string array[100];     //an array of strings
   
   FILE *file = fopen ( "eng101.txt", "r" );
   if ( file != NULL )
   {
      
    
      for (i=1 ; fgets ( line,  100,file ) != NULL ;i++ )  //for every line
      {
          
      strcpy(array[i], line);                              //copy the line as a string to the array's ith element
      }
      fclose ( file );
   }
   
   
   
   else
   {
      perror ( "eng101.txt" ); 
   }
   
   while(1);
   return 0;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main (  ){
	typedef char* 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;
}
Last edited on
I tried it but compiler gave so many errors that I can't fix :(
Fixed.
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.
Last edited on
Now there's only one, It says invalid conversion from `void*' to `char*'
( for the line 13 that is array[i]=malloc(100); )
Thanks so much!!! Working great.
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
Topic archived. No new replies allowed.