hi thanks for the help but there seems to be a problem when i put a double space in the text file it doesnt store it in the array .. but rather the last array
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[])
{
struct 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,"%299[^\n]\n",line[x].sentence);
printf("Line %d:%s\n",x,line[x].sentence);
}
fclose(in_file);
getch();
return 0;
}
example.txt
Code:
this is an example text file
what
huh
lol
2
output
Code:
Line 0:this is an example text file
Line 1:what
Line 2:huh
Line 3:lol
Line 4:2
Line 5: