Reading a file line by line in C

前端 未结 4 859
长情又很酷
长情又很酷 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: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.

提交回复
热议问题