简体   繁体   中英

PHP Convert a big binary file to a readable file

I am having problems with this simple script...

<?php
$file = "C:\\Users\\Alejandro\\Desktop\\integers\\integers";

$file = file_get_contents($file, NULL, NULL, 0, 34359738352);

echo $file;
?>

It gives me always this error:

file_get_contents(): length must be greater than or equal to zero

I am really tired, can someone help me?

EDIT: After dividing the file in 32 parts...

The error is

PHP Fatal error:  Allowed memory size of 1585446912 bytes exhausted (tried to al
locate 2147483648 bytes)

Fatal error: Allowed memory size of 1585446912 bytes exhausted (tried to allocat
e 2147483648 bytes)

EDIT (2):

Now the deal is to convert this binary file into a list of numbers from 0 to (2^31)-1 That is why I need to read the file, so I can convert the binary digits to decimal numbers.

The last argument is an int , and apparently in your implementation of PHP int only has 31 bits for magnitude. The number you provide is larger than that, so this call would never work on that system.

There are also other peculiarities:

  • why do you pass NULL for the second argument instead of false ?
  • you are saying that you want to read up to more than 2GB from that file -- is the system and PHP configuration up to doing that?

Looks like your file path is missing a backslash, which could be causing file_load_contents() to fail loading the file.

Try this instead:

$file = "C:\\\\Users\\Alejandro\\Desktop\\integers\\integers";

EDIT: Now that you can read your file, we're finding that because your file is so large, it's exceeding your memory limit and causing your script to crash.

Try buffering one piece at a time instead, so as not to exceed memory limits. Here's a script that will read binary data, one 4-byte number at a time, which you can then process to suit your needs.

By buffering only one piece at a time, you allow PHP to use only 4 bytes at a time to store the file's contents (while it processes each piece), instead of storing the entire contents in a huge buffer and causing an overflow error.

Here you go:

$file = "C:\\\\Users\\Alejandro\\Desktop\\integers\\integers";

// Open the file to read binary data
$handle = @fopen($file, "rb"); 
if ($handle) { 
   while (!feof($handle)) { 
       // Read a 4-byte number
       $bin = fgets($handle, 4);
       // Process it
       processNumber($bin); 
   } 
   fclose($handle); 
}

function processNumber($bin) {
    // Print the decimal equivalent of the number
    print(bindec($bin)); 
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM