Reading a file line by line in C

前端 未结 4 847
长情又很酷
长情又很酷 2020-12-12 01:34

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

相关标签:
4条回答
  • 2020-12-12 02:03

    why not use fopen, then just use fgets to get each line

    0 讨论(0)
  • 2020-12-12 02:04

    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]

    0 讨论(0)
  • 2020-12-12 02:17
    • Use stdio, i.e. fopen(), fgets() and fclose() to do the I/O. You're using much lower-level Posix-style I/O, for no good reason.
    • You will need to dynamically allocate each new line in order to store it in the array. You can use strdup() to do this.
    • Remember that things can go wrong; files can fail to open, lines can fail to read in, and memory can fail to be allocated. Check for this, and act accordingly.
    0 讨论(0)
  • 2020-12-12 02:23

    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.

    0 讨论(0)
提交回复
热议问题