I need to read the names, surnames and phone numbers from a text file and save them in a struct for phonebook application. The problem is without knowing how many lines the text has, how do i arrange my code so that it reads the exact number of lines as the text includes.
-
1you can read line by line using [`fgets`](https://linux.die.net/man/3/fgets) – yano Dec 26 '19 at 18:32
-
1Until the read fails, when `fgets` returns `NULL`. The idiomatic loop is `while(fgets(buffer, sizeof buffer, infile) != NULL) { /* process the input */ }` – Weather Vane Dec 26 '19 at 18:32
-
Please edit your question to include the relevant information: How does the input text file look like? What code have you already written? – flowit Dec 26 '19 at 18:32
-
May be a circular buffer https://en.wikipedia.org/wiki/Circular_buffer will help you? – TZof Dec 26 '19 at 20:58
2 Answers
Really depends on your definition of "reads the exact number of line".
[1] weather-vane stated in a comment, a while/fgets is the safest way to work... read until EOF is encountered then stop.
[2] If information is coming from a normal file you can stat(2) the file to get it's exact size before the read.
[3] (poorer solution due to risk of bugs if you guess wrong): Allocate a buffer much larger than needed and read all lines in one massive read. For safety I would zero-fill the buffer before the read and read one less byte than allocated. The "read" will return the exact number of bytes, unless all bytes requested in the read() are returned, which indicates you guessed wrong and overflowed the buffer. The chance that you read it exactly and there are no more bytes is very low.

- 3,740
- 17
- 19
An easy trick is to read the file twice. The first time you count the number of lines. Then you allocate space for storage. Then you read again and fill the space you just allocated.

- 756
- 5
- 12