I am trying to write some code that will open a file, read its content line by line and store each of these lines into an array.
First I open the file and count the
why not use fopen, then just use fgets to get each line
You haven't created an array of strings, you've created a pointer to an array of strings. you need to malloc your array in part2 to be count of lines * number of char's per line. then move your read lines into each subsequent position of array.
[edit]
one more thing.....
your strings are X length. 'C' strings aren't X length, they're X+1 length :)
[/edit]
fopen()
, fgets()
and fclose()
to do the I/O. You're using much lower-level Posix-style I/O, for no good reason.strdup()
to do this.You can use stat to get the file size. Then number_of_lines = stat.st_size/LINE_LENGTH
If you don't need your character strings nul-terminated, you can read the whole file into a single buffer. Set up the array of pointers if you really want them, or just use &buf[n * LINE_LENGTH]
to get the start of line n.
To print a non-nul terminated string of known length, you can use:
printf("line %d = '%.*s'\n", n, LINE_LENGTH, &buf[n * LINE_LENGTH]);
Let me know in a comment if you want to see actual code.