RISOLTO gets e fgets

Vito-

Utente Attivo
184
14
Ciao a tutti. Io salvo la stringa "Gita al lago con gets e ne misuro la lunghezza con strlen, il risultato é 12.
Se io prendo la stessa stringa salvata in un file con fgets e ne misuro la lunghezza con strlen il risultato é 13.
Per caso gets non salva il carattere /0?
 

Ibernato

Utente Èlite
4,330
2,047
OS
Windows 10 Pro / Ubuntu 22.04
Quindi io con fgets avro sempre un carattere in piu rispetto alla lunghezza effettiva della stringa?
Se è presente il carattere \n allora fgets lo leggerà. Lo puoi rimuovere come ha detto @Andretti60 . Basta che ti calcoli la lunghezza della stringa e fai str[len - 1] = '\0' (lo rimpiazzi con il carattere di fine stringa
Attento a come usi la gets perchè la gets è causa di Buffer overflow
 
  • Mi piace
Reazioni: Moffetta88

Vito-

Utente Attivo
184
14
Se è presente il carattere \n allora fgets lo leggerà. Lo puoi rimuovere come ha detto @Andretti60 . Basta che ti calcoli la lunghezza della stringa e fai str[len - 1] = '\0' (lo rimpiazzi con il carattere di fine stringa
Attento a come usi la gets perchè la gets è causa di Buffer overflow
Ma quindi nella stringa letta con fgets alla fine c'è il carattere di new line se io premo invio, ma altrimenti non è presente il carattere /0?


Inviato da Redmi 5 Plus tramite App ufficiale di Tom\'s Hardware Italia Forum
 

Ibernato

Utente Èlite
4,330
2,047
OS
Windows 10 Pro / Ubuntu 22.04
E invece gets non mette niente alla fine della stringa? Nemmeno /0?

Inviato da Redmi 5 Plus tramite App ufficiale di Tom\'s Hardware Italia Forum
Dal manuale:
gets() reads a line from stdin into the buffer pointed to by s
until either a terminating newline or EOF, which it replaces with
a null byte ('\0'). No check for buffer overrun is performed
(see BUGS below).

fgets invece

The fgets() function shall read bytes from stream into the array
pointed to by s until n-1 bytes are read, or a <newline> is read
and transferred to s, or an end-of-file condition is encountered.
A null byte shall be written immediately after the last byte read
into the array. If the end-of-file condition is encountered
before any bytes are read, the contents of the array pointed to
by s shall not be changed.

The fgets() function may mark the last data access timestamp of
the file associated with stream for update. The last data access
timestamp shall be marked for update by the first successful
execution of fgetc(), fgets(), fread(), fscanf(), getc(),
getchar(), getdelim(), getline(), gets(), or scanf() using stream
that returns data not supplied by a prior call to ungetc().
 

Andretti60

Utente Èlite
6,440
5,091
Apri notepad, scrivi una riga e salva senza premere ritorno dopo quella riga.
In quella situazione il carattere di ritorno NON sarà presente se leggi il file con fgets().
 

Entra

oppure Accedi utilizzando
Discord Ufficiale Entra ora!

Discussioni Simili