Jump to content

[SOLVED] Mass file open/write


disposable1

Recommended Posts

So I'm trying to make a simple game, and I've created say, ~4096 blank files in a directory. They're in coordinate form (31,3, etc), and I want to open every one separately and write some randomly generated content to it.

 

How would one go about doing that without writing 8192 lines of fopen()/fwrite()?  :)

 

And yes, I'm a n00b.  ???

Link to comment
https://forums.phpfreaks.com/topic/60239-solved-mass-file-openwrite/
Share on other sites

:) I have some code that should work perfectly. I'll set this example to work with .txt files... but you can change it to whatever extension you're using.

 

<?php
$directory = './directory/';
$dh = opendir($directory);
$files = array();
while(($file = readdir($dh)) !== FALSE){
$ext = strtolower(substr($file, strrpos($file, '.')));
if($ext==".txt") //Here's the extension that you're using for all your files.
	$files[] = $file;
}
closedir($dh);
foreach($files as $file){
$fh = fopen($directory.$file, 'w');
fwrite($fh, $DATA); //Replace $DATA with your random content...
fclose($fh);
}
?>

 

EDIT: Fixed a coding error and also... make sure all your files have the appropriate permissions set or this will fail miserably.

:) I have some code that should work perfectly. I'll set this example to work with .txt files... but you can change it to whatever extension you're using.

 

<?php
$directory = './directory/';
$dh = opendir($directory);
$files = array();
while(($file = readdir($dh)) !== FALSE){
$ext = strtolower(substr($file, strrpos($file, '.')));
if($ext==".txt") //Here's the extension that you're using for all your files.
	$files[] = $file;
}
closedir($dh);
foreach($files as $file){
$fh = fopen($directory.$file, 'w');
fwrite($fh, $DATA); //Replace $DATA with your random content...
fclose($fh);
}
?>

 

EDIT: Fixed a coding error and also... make sure all your files have the appropriate permissions set or this will fail miserably.

 

Thank you, this worked perfectly! A lot faster than I thought it would, too.  :)

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.