Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

fopen what is the b flag

Tags:

php

file-io

fopen

In reading the documentation for php fopen for php I see the following:

For portability, it is strongly recommended that you always use the 'b' flag when opening files with fopen().

What is the b flag and what does it do ?
Why is it strongly recommended ?

like image 642
nelaaro Avatar asked Apr 16 '16 04:04

nelaaro


People also ask

What does fopen () do in C?

The fopen() method in C is a library function that is used to open a file to perform various operations which include reading, writing etc. along with various modes. If the file exists then the particular file is opened else a new file is created.

What is the purpose of Mode A in fopen () function?

The fopen() function opens the file that is specified by filename . The mode parameter is a character string specifying the type of access that is requested for the file. The mode variable contains one positional parameter followed by optional keyword parameters.


1 Answers

The 'b' flag forces binary mode.

You use the 'b' flag if you want to deal with binary files, ie. an image.

Note:

When you write a text file and want to insert a line break, you need to use the correct line-ending character(s) for your operating system.

Unix based systems use \n as the line ending character, Windows based systems use \r\n as the line ending characters and Macintosh based systems use \r as the line ending character.

Windows offers a text-mode translation flag ('t') which will transparently translate \n to \r\n when working with the file.

In contrast, you can also use 'b' to force binary mode, which will not translate your data.

You can avoid the translation by using the 'b' flag in the mode parameter. Example usage:

$handle_read  = fopen($filepath, 'rb');

$handle_write = fopen("/home/user/file.gif", "wb");

So... the reason this is recommended is clearly stated on the manual:

If you do not specify the 'b' flag when working with binary files, you may experience strange problems with your data, including broken image files and strange problems with \r\n characters.

The usage of 'b' flag is also noted on manual pages of fwrite() and fread() which are binary-safe file read/write functions.

Warning:

On systems which differentiate between binary and text files (i.e. Windows) the file must be opened with 'b' included in fopen() mode parameter.

$filename = "c:\\files\\somepic.gif";
$handle   = fopen($filename, "rb");
$contents = fread($handle, filesize($filename));
fclose($handle);
like image 131
Ekin Avatar answered Oct 05 '22 22:10

Ekin