Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

fgets() and fread() - What is the difference?

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!

like image 277
Alix Axel Avatar asked May 01 '10 21:05

Alix Axel


People also ask

What are the similarities and differences between fgets () and fread () in PHP?

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.

What is the difference between read () and fread ()?

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.

What is the difference between Fscanf and fgets?

fgets reads to a newline. fscanf only reads up to whitespace.

What is fread () in PHP?

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.


2 Answers

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 :

  • If you want to read a line, from a text file, then use fgets
  • If you want to read some data (not necessarily a line) from a file, then use fread.
like image 142
Pascal MARTIN Avatar answered Sep 23 '22 18:09

Pascal MARTIN


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 .

like image 45
zloctb Avatar answered Sep 20 '22 18:09

zloctb