Ruriko
Ruriko

Reputation: 179

Create txt file listing files in subfolders

I have a directory that contains thousands of subfolders. I want to make it auto create a text file in each subfolder that will list all the files in that subfolder. I am running on Ubuntu 10.04 How can I do this in javascript or php?

Upvotes: 0

Views: 398

Answers (4)

Rahul Mahajan
Rahul Mahajan

Reputation: 109

You can achieve this by writing recursive PHP function using scandir. For more help on PHP scandir, check this

Upvotes: 0

Baba
Baba

Reputation: 95101

This is not a JOB for php .. for Experimental Purpose you can use this :

$di = new RecursiveIteratorIterator(new RecursiveDirectoryIterator(__DIR__, FilesystemIterator::SKIP_DOTS), RecursiveIteratorIterator::SELF_FIRST);
foreach ( $di as $file ) {
    $name = $file->getPathInfo() . "/files.txt";
    touch($name);
    file_put_contents($name, $file->getFilename() . PHP_EOL, FILE_APPEND);
}

If you want to remove the text file you can always run

foreach ( $di as $file ) {
    $name = $file->getPathInfo() . "/files.txt";
    is_file($name) AND unlink($name);
}

Upvotes: 1

Miqdad Ali
Miqdad Ali

Reputation: 6147

Its a sample php code which will create a file "files.txt" inside each directory and will put all the filenames in that folder ( will not add folder names).. Make sure you have write permission to all the folders

function recursive($directory)
{
    $dirs = array_diff(scandir($directory), Array( ".", ".." ));
    $dir_array = array();

    foreach($dirs as $d)
    {
        if(is_dir($directory."/".$d)){
            $dir_array[$d] = recursive($directory."/".$d);
        }
        else{
            $dir_array[$d] = $d;
            $fp = fopen("$directory/files.txt","a");
            fwrite($fp,"\n$d");
        }
    }
}   

recursive($start_directory);
?>

Upvotes: 0

ghoti
ghoti

Reputation: 46846

In shell, it's a single command (albeit one that embeds other commands):

find /start/path -type d -exec sh -c "ls {} > {}/files.txt" \;

If you really need this in another language, please clarify your requirements.

Upvotes: 3

Related Questions