3

Has anyone written a Fast Algorithm that generates a LARGE dummy file in PHP, say 500MB-2GB?

tshepang
  • 12,111
  • 21
  • 91
  • 136
macki
  • 904
  • 7
  • 12

2 Answers2

12

If you don't care about the file contents at all, you can just seek to any position and write something:

$f = fopen('largefile', 'wb');
fseek($f, 2 * 1000 * 1000 * 1000, SEEK_SET);
fwrite($f, 'after 2 GB');
fclose($f);

If the OS and filesystem support sparse files, the file will be really big, but not actually take more than a couple of bytes of disk space.

phihag
  • 278,196
  • 72
  • 453
  • 469
  • Dope function, but technically, that's not 2GB. – Mob Nov 18 '11 at 14:45
  • @Mob Huh? This writes 2GB + 10 Bytes. If you want to write exactly 2GB, you can either call `ftruncate` instead of `fwrite` or write 2G-1 bytes and call `fwrite('\0')`. – phihag Nov 18 '11 at 22:12
  • On UNIX/Linux this would create a file of 10 bytes with a 2GB leading hole in it. This may or may not be what you want. – Rich Homolka May 29 '12 at 15:53
  • @Rich Homolka Define hole. It's a file with 2 billion null bytes + 10 extra bytes, isn't it? And I definitely disagree with your statement that it only depends on the OS. As I wrote in the answer, the filesystem must support sparse files as well. For example, with Linux 3.3 on a FAT32 drive, this code will create a file that takes up 2GB of disk space. – phihag May 29 '12 at 16:38
0
 /* far too long to file creation , do not use especially not
$f = fopen('largefile', 'wb');
        fseek($f, 2 * 1000 * 1000 * 1000, SEEK_SET);
        fwrite($f, 'after 2 GB');
        fclose($f);*/

^^ The best feature is here with 0s to create a 4GB file ^^

FUNCTION CreatFileDummy($file_name,$size) {   
// 32bits 4 294 967 296 bytes MAX Size
    $f = fopen($file_name, 'wb');
    if($size >= 1000000000)  {
        $z = ($size / 1000000000);       
        if (is_float($z))  {
            $z = round($z,0);
            fseek($f, ( $size - ($z * 1000000000) -1 ), SEEK_END);
            fwrite($f, "\0");
        }       
        while(--$z > -1) {
            fseek($f, 999999999, SEEK_END);
            fwrite($f, "\0");
        }
    }
    else {
        fseek($f, $size - 1, SEEK_END);
        fwrite($f, "\0");
    }
    fclose($f);

Return true;
}

test it ^^ Max in Php 32bit 4 294 967 296 :

CreatFileDummy('mydummyfile.iso',4294967296);

You want Write , Read and Creat File Dummy my code is here ^^ :

https://github.com/Darksynx/php

Darksynx
  • 68
  • 5