You are not logged in.
Pages: 1
For reading a line from stdin, do most people use the unsafe but standard fgets or the safe but gcc-specific (or at least non-standard) getline?
Offline
how exactly would fgets be unsafe ? the second argument to fgets is the buffer size, gets on the other hand can give you troubles.
Offline
Oh, a bunch of sites I was browsing said you can only use fgets when you've checked to make sure there's no null character in the input.
Offline
fgets() shouldn't care about '\0's.
fgets() reads in at most one less than size characters from stream and stores them into the buffer
pointed to by s. Reading stops after an EOF or a newline. If a newline is read, it is stored into
the buffer. A '\0' is stored after the last character in the buffer.
But of course -- this means that the input stored in your buffer might contain '\0'-s. So perhaps that's what was meant on your nameless forums (:
Offline
All right, so C programmers generally use fgets? gnud, I never said anything about forums. One such site was <http://www.gnu.org/software/libtool/man … Input.html>
Offline
fgets is safe and can handle '\0's just fine, the reason for the warning is due to the fact that fgets places a '\0' in the buffer to indicate the last character it read, rather than returning the number of characters read. so unless you know how much data to expect beforehand or you initialize your buffer with some other character that you're sure is not in the file, then if your file contains a '\0' you will not be able to tell what was the last character read in by fgets.
for example, say you have a buffer of 6 chars all set to '*'
you also have a file with the following characters
'a' 'b' '\0' 'd' 'e'
calling fgets(buf,5,file) will leave the following data in your buffer
'a' 'b' '\0' 'd' '\0' '*'
since the buffer was initialized with '*'s we know the second '\0' is the one fgets left to mark the last character read in. if it was initialized with '\0's or random data and you didn't know how much data to expect, then you wouldn't be able to know this for sure
edit: whoops, wouldn't have posted this if i had noticed gnud had already given an explanation for this
Last edited by e_tank (2009-01-14 00:19:34)
Offline
Ah, that makes sense. Thanks for the explanation.
Offline
Pages: 1