I understand the differences between fgets()
and fgetss()
but I don't get the difference between fgets()
and fread()
, can someone please clarify this subject? Which one is faster? Thanks!
When to use fgets and fread? If the user wishes to read a line from a text file, it is suggested to use the 'fgets' function. On the other hand, if the user wishes to read some data (which need not be a line) from a file, then the 'fread' function can be used.
read() is a low level, unbuffered read. It makes a direct system call on UNIX. fread() is part of the C library, and provides buffered reads. It is usually implemented by calling read() in order to fill its buffer.
fgets reads to a newline. fscanf only reads up to whitespace.
The fread() function reads from an open file. The fread() function halts at the end of the file or when it reaches the specified length whichever comes first. It returns the read string on success.
fgets
reads a line -- i.e. it will stop at a newline.
fread
reads raw data -- it will stop after a specified (or default) number of bytes, independently of any newline that might or might not be present.
Speed is not a reason to use one over the other, as those two functions just don't do the same thing :
fgets
fread
.fread() for binary data and fread has a limit on how many chars you can read
$source_file = fopen( $filename, "r" ) or die("Couldn't open $filename"); while (!feof($source_file)) { $buffer = fread($source_file, 5); var_dump($buffer); //return string with length 5 chars! }
Number 5 is length bytes have been read .
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With