printing out a line from text file..
i want to open a txt file and then store each line in the file into an array of structs.. this iswhat i have so far
Code:
#include <conio.h>
#include <stdio.h>
#include <stdlib.h>
struct input{
char *sentence[300];
};
int num_lines(char name[]) // this function counts the number of lines in file
{
int ch, prev = '\n', lines = 0;
FILE *in_file;
in_file = fopen(name, "r");
if (in_file == NULL) {
fprintf(stderr, "Unable to locate the file!\n");
exit(8);
}
while ( (ch = fgetc(in_file)) != EOF ) { // read chars in file
if ( ch == '\n' )
{
++lines; // counter
}
prev = ch;
}
fclose(in_file);
if ( prev != '\n' ) // if last line did not end in new line
{
++lines;
}
return lines;
}
int main(int argc, char *argv[])
{
input line[500];
int numline,x;
numline = num_lines(argv[1]);
FILE *in_file;
in_file = fopen(argv[1], "r");
if (in_file == NULL) {
fprintf(stderr, "Unable to locate the file!\n");
exit(8);
}
for(x=0;x<numline;x++)
{
fscanf(in_file,"%300[^\n]s",line[x].sentence);
printf("Line %d:%s\n",x,line[x].sentence);
}
fclose(in_file);
getch();
return 0;
}
when i run it it seems to only store in array 0.. whats wrong? if any1 knows the solution can you plz explain it in detail as im a beginner ty appreciate it.