Fgetc (): Read and save string of unknown length

What I need to do for an appointment:

  • open file (using fopen () function)
  • read student name (using fgetc ())
  • save this name in some part of the structure

The problem is that I need to read an arbitrary long line in the name, and I do not know how to save this line without losing memory (or writing to unallocated memory).

EDIT

My first idea was to allocate a 1-byte (char) block of memory, and then call realloc () if more bytes are needed, but that doesn't seem very efficient. Or maybe I could double the array if it is full, and then at the end copy the characters to a new memory block of the exact size.

+3
source share
3

, 100 1000 , , , . , , , .

Do . . !

, , malloc , ( ).

, realloc. .. malloc 50 .

, , realloc, . , , 50 , int , , , . - , , .

+5

, , , , , , . -, fgetc, fread .. O/S.

, , ( ), . , , malloc, , .

, - , !

, , , , , . .

+2

, :

char name_buffer [ 80 ];

, ( , ) 80 . , , , .

, , :

int chars_read = 0; /* most compilers will init to 0 for you, but always good to be explicit */

fgetc(), 80 (79 , ). , , .

while ( ( chars_read < 80 ) && ( !feof( stdin ) ) ) {
  name_buffer [ chars_read ] = fgetc ( stdin );
  chars_read++;
}
if ( chars_read < 80 )
  name_buffer [ chars_read ] = '\0'; /* terminating null character */

, stdin. , , , , (, ) .. , , , .

, , , - /, . malloc realloc, , , , - NULL, .. , , , . , , , - .

+2

Source: https://habr.com/ru/post/1776312/


All Articles