Instruction
stringlengths
45
106
input_code
stringlengths
1
13.7k
output_code
stringlengths
1
13.7k
Please provide an equivalent version of this Perl code in C++.
use File::Find qw(find); my $dir = '.'; my $pattern = 'foo'; my $callback = sub { print $File::Find::name, "\n" if /$pattern/ }; find $callback, $dir;
#include "boost/filesystem.hpp" #include "boost/regex.hpp" #include <iostream> using namespace boost::filesystem; int main() { path current_dir("."); boost::regex pattern("a.*"); for (recursive_directory_iterator iter(current_dir), end; iter != end; ++iter) { std::string name = iter->path().filename().string(); if (regex_match(name, pattern)) std::cout << iter->path() << "\n"; } }
Generate an equivalent Java version of this Perl code.
use File::Find qw(find); my $dir = '.'; my $pattern = 'foo'; my $callback = sub { print $File::Find::name, "\n" if /$pattern/ }; find $callback, $dir;
import java.io.File; public class MainEntry { public static void main(String[] args) { walkin(new File("/home/user")); } public static void walkin(File dir) { String pattern = ".mp3"; File listFile[] = dir.listFiles(); if (listFile != null) { for (int i=0; i<listFile.length; i++) { if (listFile[i].isDirectory()) { walkin(listFile[i]); } else { if (listFile[i].getName().endsWith(pattern)) { System.out.println(listFile[i].getPath()); } } } } } }
Write a version of this Perl function in Python with identical behavior.
use File::Find qw(find); my $dir = '.'; my $pattern = 'foo'; my $callback = sub { print $File::Find::name, "\n" if /$pattern/ }; find $callback, $dir;
from pathlib import Path for path in Path('.').rglob('*.*'): print(path)
Ensure the translated VB code behaves exactly like the original Perl snippet.
use File::Find qw(find); my $dir = '.'; my $pattern = 'foo'; my $callback = sub { print $File::Find::name, "\n" if /$pattern/ }; find $callback, $dir;
Sub printFiles(parentDir As FolderItem, pattern As String) For i As Integer = 1 To parentDir.Count If parentDir.Item(i).Directory Then printFiles(parentDir.Item(i), pattern) Else Dim rg as New RegEx Dim myMatch as RegExMatch rg.SearchPattern = pattern myMatch = rg.search(parentDir.Item(i).Name) If myMatch <> Nil Then Print(parentDir.Item(i).AbsolutePath) End If Next End Sub
Transform the following Perl implementation into Go, maintaining the same output and logic.
use File::Find qw(find); my $dir = '.'; my $pattern = 'foo'; my $callback = sub { print $File::Find::name, "\n" if /$pattern/ }; find $callback, $dir;
package main import ( "fmt" "os" "path/filepath" ) func VisitFile(fp string, fi os.FileInfo, err error) error { if err != nil { fmt.Println(err) return nil } if fi.IsDir() { return nil } matched, err := filepath.Match("*.mp3", fi.Name()) if err != nil { fmt.Println(err) return err } if matched { fmt.Println(fp) } return nil } func main() { filepath.Walk("/", VisitFile) }
Keep all operations the same but rewrite the snippet in C.
Get-ChildItem -Recurse -Include *.mp3
#include <sys/types.h> #include <sys/stat.h> #include <unistd.h> #include <dirent.h> #include <regex.h> #include <stdio.h> #include <string.h> #include <errno.h> #include <err.h> enum { WALK_OK = 0, WALK_BADPATTERN, WALK_NAMETOOLONG, WALK_BADIO, }; #define WS_NONE 0 #define WS_RECURSIVE (1 << 0) #define WS_DEFAULT WS_RECURSIVE #define WS_FOLLOWLINK (1 << 1) #define WS_DOTFILES (1 << 2) #define WS_MATCHDIRS (1 << 3) int walk_recur(char *dname, regex_t *reg, int spec) { struct dirent *dent; DIR *dir; struct stat st; char fn[FILENAME_MAX]; int res = WALK_OK; int len = strlen(dname); if (len >= FILENAME_MAX - 1) return WALK_NAMETOOLONG; strcpy(fn, dname); fn[len++] = '/'; if (!(dir = opendir(dname))) { warn("can't open %s", dname); return WALK_BADIO; } errno = 0; while ((dent = readdir(dir))) { if (!(spec & WS_DOTFILES) && dent->d_name[0] == '.') continue; if (!strcmp(dent->d_name, ".") || !strcmp(dent->d_name, "..")) continue; strncpy(fn + len, dent->d_name, FILENAME_MAX - len); if (lstat(fn, &st) == -1) { warn("Can't stat %s", fn); res = WALK_BADIO; continue; } if (S_ISLNK(st.st_mode) && !(spec & WS_FOLLOWLINK)) continue; if (S_ISDIR(st.st_mode)) { if ((spec & WS_RECURSIVE)) walk_recur(fn, reg, spec); if (!(spec & WS_MATCHDIRS)) continue; } if (!regexec(reg, fn, 0, 0, 0)) puts(fn); } if (dir) closedir(dir); return res ? res : errno ? WALK_BADIO : WALK_OK; } int walk_dir(char *dname, char *pattern, int spec) { regex_t r; int res; if (regcomp(&r, pattern, REG_EXTENDED | REG_NOSUB)) return WALK_BADPATTERN; res = walk_recur(dname, &r, spec); regfree(&r); return res; } int main() { int r = walk_dir(".", ".\\.c$", WS_DEFAULT|WS_MATCHDIRS); switch(r) { case WALK_OK: break; case WALK_BADIO: err(1, "IO error"); case WALK_BADPATTERN: err(1, "Bad pattern"); case WALK_NAMETOOLONG: err(1, "Filename too long"); default: err(1, "Unknown error?"); } return 0; }
Change the following PowerShell code into C# without altering its purpose.
Get-ChildItem -Recurse -Include *.mp3
using System; using System.Collections.Generic; using System.IO; using System.Linq; namespace RosettaRecursiveDirectory { class Program { static IEnumerable<FileInfo> TraverseDirectory(string rootPath, Func<FileInfo, bool> Pattern) { var directoryStack = new Stack<DirectoryInfo>(); directoryStack.Push(new DirectoryInfo(rootPath)); while (directoryStack.Count > 0) { var dir = directoryStack.Pop(); try { foreach (var i in dir.GetDirectories()) directoryStack.Push(i); } catch (UnauthorizedAccessException) { continue; } foreach (var f in dir.GetFiles().Where(Pattern)) yield return f; } } static void Main(string[] args) { foreach (var file in TraverseDirectory(@"C:\Windows", f => f.Extension == ".wmv")) Console.WriteLine(file.FullName); Console.WriteLine("Done."); } } }
Convert the following code from PowerShell to C++, ensuring the logic remains intact.
Get-ChildItem -Recurse -Include *.mp3
#include "boost/filesystem.hpp" #include "boost/regex.hpp" #include <iostream> using namespace boost::filesystem; int main() { path current_dir("."); boost::regex pattern("a.*"); for (recursive_directory_iterator iter(current_dir), end; iter != end; ++iter) { std::string name = iter->path().filename().string(); if (regex_match(name, pattern)) std::cout << iter->path() << "\n"; } }
Ensure the translated Java code behaves exactly like the original PowerShell snippet.
Get-ChildItem -Recurse -Include *.mp3
import java.io.File; public class MainEntry { public static void main(String[] args) { walkin(new File("/home/user")); } public static void walkin(File dir) { String pattern = ".mp3"; File listFile[] = dir.listFiles(); if (listFile != null) { for (int i=0; i<listFile.length; i++) { if (listFile[i].isDirectory()) { walkin(listFile[i]); } else { if (listFile[i].getName().endsWith(pattern)) { System.out.println(listFile[i].getPath()); } } } } } }
Keep all operations the same but rewrite the snippet in Python.
Get-ChildItem -Recurse -Include *.mp3
from pathlib import Path for path in Path('.').rglob('*.*'): print(path)
Maintain the same structure and functionality when rewriting this code in VB.
Get-ChildItem -Recurse -Include *.mp3
Sub printFiles(parentDir As FolderItem, pattern As String) For i As Integer = 1 To parentDir.Count If parentDir.Item(i).Directory Then printFiles(parentDir.Item(i), pattern) Else Dim rg as New RegEx Dim myMatch as RegExMatch rg.SearchPattern = pattern myMatch = rg.search(parentDir.Item(i).Name) If myMatch <> Nil Then Print(parentDir.Item(i).AbsolutePath) End If Next End Sub
Rewrite the snippet below in Go so it works the same as the original PowerShell code.
Get-ChildItem -Recurse -Include *.mp3
package main import ( "fmt" "os" "path/filepath" ) func VisitFile(fp string, fi os.FileInfo, err error) error { if err != nil { fmt.Println(err) return nil } if fi.IsDir() { return nil } matched, err := filepath.Match("*.mp3", fi.Name()) if err != nil { fmt.Println(err) return err } if matched { fmt.Println(fp) } return nil } func main() { filepath.Walk("/", VisitFile) }
Translate the given R code snippet into C without altering its behavior.
dir("/bar/foo", "mp3",recursive=T)
#include <sys/types.h> #include <sys/stat.h> #include <unistd.h> #include <dirent.h> #include <regex.h> #include <stdio.h> #include <string.h> #include <errno.h> #include <err.h> enum { WALK_OK = 0, WALK_BADPATTERN, WALK_NAMETOOLONG, WALK_BADIO, }; #define WS_NONE 0 #define WS_RECURSIVE (1 << 0) #define WS_DEFAULT WS_RECURSIVE #define WS_FOLLOWLINK (1 << 1) #define WS_DOTFILES (1 << 2) #define WS_MATCHDIRS (1 << 3) int walk_recur(char *dname, regex_t *reg, int spec) { struct dirent *dent; DIR *dir; struct stat st; char fn[FILENAME_MAX]; int res = WALK_OK; int len = strlen(dname); if (len >= FILENAME_MAX - 1) return WALK_NAMETOOLONG; strcpy(fn, dname); fn[len++] = '/'; if (!(dir = opendir(dname))) { warn("can't open %s", dname); return WALK_BADIO; } errno = 0; while ((dent = readdir(dir))) { if (!(spec & WS_DOTFILES) && dent->d_name[0] == '.') continue; if (!strcmp(dent->d_name, ".") || !strcmp(dent->d_name, "..")) continue; strncpy(fn + len, dent->d_name, FILENAME_MAX - len); if (lstat(fn, &st) == -1) { warn("Can't stat %s", fn); res = WALK_BADIO; continue; } if (S_ISLNK(st.st_mode) && !(spec & WS_FOLLOWLINK)) continue; if (S_ISDIR(st.st_mode)) { if ((spec & WS_RECURSIVE)) walk_recur(fn, reg, spec); if (!(spec & WS_MATCHDIRS)) continue; } if (!regexec(reg, fn, 0, 0, 0)) puts(fn); } if (dir) closedir(dir); return res ? res : errno ? WALK_BADIO : WALK_OK; } int walk_dir(char *dname, char *pattern, int spec) { regex_t r; int res; if (regcomp(&r, pattern, REG_EXTENDED | REG_NOSUB)) return WALK_BADPATTERN; res = walk_recur(dname, &r, spec); regfree(&r); return res; } int main() { int r = walk_dir(".", ".\\.c$", WS_DEFAULT|WS_MATCHDIRS); switch(r) { case WALK_OK: break; case WALK_BADIO: err(1, "IO error"); case WALK_BADPATTERN: err(1, "Bad pattern"); case WALK_NAMETOOLONG: err(1, "Filename too long"); default: err(1, "Unknown error?"); } return 0; }
Write the same algorithm in C# as shown in this R implementation.
dir("/bar/foo", "mp3",recursive=T)
using System; using System.Collections.Generic; using System.IO; using System.Linq; namespace RosettaRecursiveDirectory { class Program { static IEnumerable<FileInfo> TraverseDirectory(string rootPath, Func<FileInfo, bool> Pattern) { var directoryStack = new Stack<DirectoryInfo>(); directoryStack.Push(new DirectoryInfo(rootPath)); while (directoryStack.Count > 0) { var dir = directoryStack.Pop(); try { foreach (var i in dir.GetDirectories()) directoryStack.Push(i); } catch (UnauthorizedAccessException) { continue; } foreach (var f in dir.GetFiles().Where(Pattern)) yield return f; } } static void Main(string[] args) { foreach (var file in TraverseDirectory(@"C:\Windows", f => f.Extension == ".wmv")) Console.WriteLine(file.FullName); Console.WriteLine("Done."); } } }
Keep all operations the same but rewrite the snippet in C++.
dir("/bar/foo", "mp3",recursive=T)
#include "boost/filesystem.hpp" #include "boost/regex.hpp" #include <iostream> using namespace boost::filesystem; int main() { path current_dir("."); boost::regex pattern("a.*"); for (recursive_directory_iterator iter(current_dir), end; iter != end; ++iter) { std::string name = iter->path().filename().string(); if (regex_match(name, pattern)) std::cout << iter->path() << "\n"; } }
Translate the given R code snippet into Java without altering its behavior.
dir("/bar/foo", "mp3",recursive=T)
import java.io.File; public class MainEntry { public static void main(String[] args) { walkin(new File("/home/user")); } public static void walkin(File dir) { String pattern = ".mp3"; File listFile[] = dir.listFiles(); if (listFile != null) { for (int i=0; i<listFile.length; i++) { if (listFile[i].isDirectory()) { walkin(listFile[i]); } else { if (listFile[i].getName().endsWith(pattern)) { System.out.println(listFile[i].getPath()); } } } } } }
Write the same code in Python as shown below in R.
dir("/bar/foo", "mp3",recursive=T)
from pathlib import Path for path in Path('.').rglob('*.*'): print(path)
Maintain the same structure and functionality when rewriting this code in VB.
dir("/bar/foo", "mp3",recursive=T)
Sub printFiles(parentDir As FolderItem, pattern As String) For i As Integer = 1 To parentDir.Count If parentDir.Item(i).Directory Then printFiles(parentDir.Item(i), pattern) Else Dim rg as New RegEx Dim myMatch as RegExMatch rg.SearchPattern = pattern myMatch = rg.search(parentDir.Item(i).Name) If myMatch <> Nil Then Print(parentDir.Item(i).AbsolutePath) End If Next End Sub
Rewrite this program in Go while keeping its functionality equivalent to the R version.
dir("/bar/foo", "mp3",recursive=T)
package main import ( "fmt" "os" "path/filepath" ) func VisitFile(fp string, fi os.FileInfo, err error) error { if err != nil { fmt.Println(err) return nil } if fi.IsDir() { return nil } matched, err := filepath.Match("*.mp3", fi.Name()) if err != nil { fmt.Println(err) return err } if matched { fmt.Println(fp) } return nil } func main() { filepath.Walk("/", VisitFile) }
Please provide an equivalent version of this Racket code in C.
-> (for ([f (in-directory "/tmp")] #:when (regexp-match? "\\.rkt$" f)) (displayln f)) ... *.rkt files including in nested directories ...
#include <sys/types.h> #include <sys/stat.h> #include <unistd.h> #include <dirent.h> #include <regex.h> #include <stdio.h> #include <string.h> #include <errno.h> #include <err.h> enum { WALK_OK = 0, WALK_BADPATTERN, WALK_NAMETOOLONG, WALK_BADIO, }; #define WS_NONE 0 #define WS_RECURSIVE (1 << 0) #define WS_DEFAULT WS_RECURSIVE #define WS_FOLLOWLINK (1 << 1) #define WS_DOTFILES (1 << 2) #define WS_MATCHDIRS (1 << 3) int walk_recur(char *dname, regex_t *reg, int spec) { struct dirent *dent; DIR *dir; struct stat st; char fn[FILENAME_MAX]; int res = WALK_OK; int len = strlen(dname); if (len >= FILENAME_MAX - 1) return WALK_NAMETOOLONG; strcpy(fn, dname); fn[len++] = '/'; if (!(dir = opendir(dname))) { warn("can't open %s", dname); return WALK_BADIO; } errno = 0; while ((dent = readdir(dir))) { if (!(spec & WS_DOTFILES) && dent->d_name[0] == '.') continue; if (!strcmp(dent->d_name, ".") || !strcmp(dent->d_name, "..")) continue; strncpy(fn + len, dent->d_name, FILENAME_MAX - len); if (lstat(fn, &st) == -1) { warn("Can't stat %s", fn); res = WALK_BADIO; continue; } if (S_ISLNK(st.st_mode) && !(spec & WS_FOLLOWLINK)) continue; if (S_ISDIR(st.st_mode)) { if ((spec & WS_RECURSIVE)) walk_recur(fn, reg, spec); if (!(spec & WS_MATCHDIRS)) continue; } if (!regexec(reg, fn, 0, 0, 0)) puts(fn); } if (dir) closedir(dir); return res ? res : errno ? WALK_BADIO : WALK_OK; } int walk_dir(char *dname, char *pattern, int spec) { regex_t r; int res; if (regcomp(&r, pattern, REG_EXTENDED | REG_NOSUB)) return WALK_BADPATTERN; res = walk_recur(dname, &r, spec); regfree(&r); return res; } int main() { int r = walk_dir(".", ".\\.c$", WS_DEFAULT|WS_MATCHDIRS); switch(r) { case WALK_OK: break; case WALK_BADIO: err(1, "IO error"); case WALK_BADPATTERN: err(1, "Bad pattern"); case WALK_NAMETOOLONG: err(1, "Filename too long"); default: err(1, "Unknown error?"); } return 0; }
Translate the given Racket code snippet into C# without altering its behavior.
-> (for ([f (in-directory "/tmp")] #:when (regexp-match? "\\.rkt$" f)) (displayln f)) ... *.rkt files including in nested directories ...
using System; using System.Collections.Generic; using System.IO; using System.Linq; namespace RosettaRecursiveDirectory { class Program { static IEnumerable<FileInfo> TraverseDirectory(string rootPath, Func<FileInfo, bool> Pattern) { var directoryStack = new Stack<DirectoryInfo>(); directoryStack.Push(new DirectoryInfo(rootPath)); while (directoryStack.Count > 0) { var dir = directoryStack.Pop(); try { foreach (var i in dir.GetDirectories()) directoryStack.Push(i); } catch (UnauthorizedAccessException) { continue; } foreach (var f in dir.GetFiles().Where(Pattern)) yield return f; } } static void Main(string[] args) { foreach (var file in TraverseDirectory(@"C:\Windows", f => f.Extension == ".wmv")) Console.WriteLine(file.FullName); Console.WriteLine("Done."); } } }
Change the programming language of this snippet from Racket to C++ without modifying what it does.
-> (for ([f (in-directory "/tmp")] #:when (regexp-match? "\\.rkt$" f)) (displayln f)) ... *.rkt files including in nested directories ...
#include "boost/filesystem.hpp" #include "boost/regex.hpp" #include <iostream> using namespace boost::filesystem; int main() { path current_dir("."); boost::regex pattern("a.*"); for (recursive_directory_iterator iter(current_dir), end; iter != end; ++iter) { std::string name = iter->path().filename().string(); if (regex_match(name, pattern)) std::cout << iter->path() << "\n"; } }
Convert this Racket snippet to Java and keep its semantics consistent.
-> (for ([f (in-directory "/tmp")] #:when (regexp-match? "\\.rkt$" f)) (displayln f)) ... *.rkt files including in nested directories ...
import java.io.File; public class MainEntry { public static void main(String[] args) { walkin(new File("/home/user")); } public static void walkin(File dir) { String pattern = ".mp3"; File listFile[] = dir.listFiles(); if (listFile != null) { for (int i=0; i<listFile.length; i++) { if (listFile[i].isDirectory()) { walkin(listFile[i]); } else { if (listFile[i].getName().endsWith(pattern)) { System.out.println(listFile[i].getPath()); } } } } } }
Translate this program into Python but keep the logic exactly as in Racket.
-> (for ([f (in-directory "/tmp")] #:when (regexp-match? "\\.rkt$" f)) (displayln f)) ... *.rkt files including in nested directories ...
from pathlib import Path for path in Path('.').rglob('*.*'): print(path)
Keep all operations the same but rewrite the snippet in VB.
-> (for ([f (in-directory "/tmp")] #:when (regexp-match? "\\.rkt$" f)) (displayln f)) ... *.rkt files including in nested directories ...
Sub printFiles(parentDir As FolderItem, pattern As String) For i As Integer = 1 To parentDir.Count If parentDir.Item(i).Directory Then printFiles(parentDir.Item(i), pattern) Else Dim rg as New RegEx Dim myMatch as RegExMatch rg.SearchPattern = pattern myMatch = rg.search(parentDir.Item(i).Name) If myMatch <> Nil Then Print(parentDir.Item(i).AbsolutePath) End If Next End Sub
Maintain the same structure and functionality when rewriting this code in Go.
-> (for ([f (in-directory "/tmp")] #:when (regexp-match? "\\.rkt$" f)) (displayln f)) ... *.rkt files including in nested directories ...
package main import ( "fmt" "os" "path/filepath" ) func VisitFile(fp string, fi os.FileInfo, err error) error { if err != nil { fmt.Println(err) return nil } if fi.IsDir() { return nil } matched, err := filepath.Match("*.mp3", fi.Name()) if err != nil { fmt.Println(err) return err } if matched { fmt.Println(fp) } return nil } func main() { filepath.Walk("/", VisitFile) }
Ensure the translated C code behaves exactly like the original REXX snippet.
* List all file names on my disk D: that contain the string TTTT *--------------------------------------------------------------------*/ call SysFileTree "d:\*.*", "file", "FS" -- F get all Files -- S search subdirectories Say file.0 'files on disk' do i=1 to file.0 If pos('TTTT',translate(file.i))>0 Then say file.i end
#include <sys/types.h> #include <sys/stat.h> #include <unistd.h> #include <dirent.h> #include <regex.h> #include <stdio.h> #include <string.h> #include <errno.h> #include <err.h> enum { WALK_OK = 0, WALK_BADPATTERN, WALK_NAMETOOLONG, WALK_BADIO, }; #define WS_NONE 0 #define WS_RECURSIVE (1 << 0) #define WS_DEFAULT WS_RECURSIVE #define WS_FOLLOWLINK (1 << 1) #define WS_DOTFILES (1 << 2) #define WS_MATCHDIRS (1 << 3) int walk_recur(char *dname, regex_t *reg, int spec) { struct dirent *dent; DIR *dir; struct stat st; char fn[FILENAME_MAX]; int res = WALK_OK; int len = strlen(dname); if (len >= FILENAME_MAX - 1) return WALK_NAMETOOLONG; strcpy(fn, dname); fn[len++] = '/'; if (!(dir = opendir(dname))) { warn("can't open %s", dname); return WALK_BADIO; } errno = 0; while ((dent = readdir(dir))) { if (!(spec & WS_DOTFILES) && dent->d_name[0] == '.') continue; if (!strcmp(dent->d_name, ".") || !strcmp(dent->d_name, "..")) continue; strncpy(fn + len, dent->d_name, FILENAME_MAX - len); if (lstat(fn, &st) == -1) { warn("Can't stat %s", fn); res = WALK_BADIO; continue; } if (S_ISLNK(st.st_mode) && !(spec & WS_FOLLOWLINK)) continue; if (S_ISDIR(st.st_mode)) { if ((spec & WS_RECURSIVE)) walk_recur(fn, reg, spec); if (!(spec & WS_MATCHDIRS)) continue; } if (!regexec(reg, fn, 0, 0, 0)) puts(fn); } if (dir) closedir(dir); return res ? res : errno ? WALK_BADIO : WALK_OK; } int walk_dir(char *dname, char *pattern, int spec) { regex_t r; int res; if (regcomp(&r, pattern, REG_EXTENDED | REG_NOSUB)) return WALK_BADPATTERN; res = walk_recur(dname, &r, spec); regfree(&r); return res; } int main() { int r = walk_dir(".", ".\\.c$", WS_DEFAULT|WS_MATCHDIRS); switch(r) { case WALK_OK: break; case WALK_BADIO: err(1, "IO error"); case WALK_BADPATTERN: err(1, "Bad pattern"); case WALK_NAMETOOLONG: err(1, "Filename too long"); default: err(1, "Unknown error?"); } return 0; }
Change the programming language of this snippet from REXX to C# without modifying what it does.
* List all file names on my disk D: that contain the string TTTT *--------------------------------------------------------------------*/ call SysFileTree "d:\*.*", "file", "FS" -- F get all Files -- S search subdirectories Say file.0 'files on disk' do i=1 to file.0 If pos('TTTT',translate(file.i))>0 Then say file.i end
using System; using System.Collections.Generic; using System.IO; using System.Linq; namespace RosettaRecursiveDirectory { class Program { static IEnumerable<FileInfo> TraverseDirectory(string rootPath, Func<FileInfo, bool> Pattern) { var directoryStack = new Stack<DirectoryInfo>(); directoryStack.Push(new DirectoryInfo(rootPath)); while (directoryStack.Count > 0) { var dir = directoryStack.Pop(); try { foreach (var i in dir.GetDirectories()) directoryStack.Push(i); } catch (UnauthorizedAccessException) { continue; } foreach (var f in dir.GetFiles().Where(Pattern)) yield return f; } } static void Main(string[] args) { foreach (var file in TraverseDirectory(@"C:\Windows", f => f.Extension == ".wmv")) Console.WriteLine(file.FullName); Console.WriteLine("Done."); } } }
Port the following code from REXX to C++ with equivalent syntax and logic.
* List all file names on my disk D: that contain the string TTTT *--------------------------------------------------------------------*/ call SysFileTree "d:\*.*", "file", "FS" -- F get all Files -- S search subdirectories Say file.0 'files on disk' do i=1 to file.0 If pos('TTTT',translate(file.i))>0 Then say file.i end
#include "boost/filesystem.hpp" #include "boost/regex.hpp" #include <iostream> using namespace boost::filesystem; int main() { path current_dir("."); boost::regex pattern("a.*"); for (recursive_directory_iterator iter(current_dir), end; iter != end; ++iter) { std::string name = iter->path().filename().string(); if (regex_match(name, pattern)) std::cout << iter->path() << "\n"; } }
Translate this program into Java but keep the logic exactly as in REXX.
* List all file names on my disk D: that contain the string TTTT *--------------------------------------------------------------------*/ call SysFileTree "d:\*.*", "file", "FS" -- F get all Files -- S search subdirectories Say file.0 'files on disk' do i=1 to file.0 If pos('TTTT',translate(file.i))>0 Then say file.i end
import java.io.File; public class MainEntry { public static void main(String[] args) { walkin(new File("/home/user")); } public static void walkin(File dir) { String pattern = ".mp3"; File listFile[] = dir.listFiles(); if (listFile != null) { for (int i=0; i<listFile.length; i++) { if (listFile[i].isDirectory()) { walkin(listFile[i]); } else { if (listFile[i].getName().endsWith(pattern)) { System.out.println(listFile[i].getPath()); } } } } } }
Write the same code in Python as shown below in REXX.
* List all file names on my disk D: that contain the string TTTT *--------------------------------------------------------------------*/ call SysFileTree "d:\*.*", "file", "FS" -- F get all Files -- S search subdirectories Say file.0 'files on disk' do i=1 to file.0 If pos('TTTT',translate(file.i))>0 Then say file.i end
from pathlib import Path for path in Path('.').rglob('*.*'): print(path)
Can you help me rewrite this code in VB instead of REXX, keeping it the same logically?
* List all file names on my disk D: that contain the string TTTT *--------------------------------------------------------------------*/ call SysFileTree "d:\*.*", "file", "FS" -- F get all Files -- S search subdirectories Say file.0 'files on disk' do i=1 to file.0 If pos('TTTT',translate(file.i))>0 Then say file.i end
Sub printFiles(parentDir As FolderItem, pattern As String) For i As Integer = 1 To parentDir.Count If parentDir.Item(i).Directory Then printFiles(parentDir.Item(i), pattern) Else Dim rg as New RegEx Dim myMatch as RegExMatch rg.SearchPattern = pattern myMatch = rg.search(parentDir.Item(i).Name) If myMatch <> Nil Then Print(parentDir.Item(i).AbsolutePath) End If Next End Sub
Transform the following REXX implementation into Go, maintaining the same output and logic.
* List all file names on my disk D: that contain the string TTTT *--------------------------------------------------------------------*/ call SysFileTree "d:\*.*", "file", "FS" -- F get all Files -- S search subdirectories Say file.0 'files on disk' do i=1 to file.0 If pos('TTTT',translate(file.i))>0 Then say file.i end
package main import ( "fmt" "os" "path/filepath" ) func VisitFile(fp string, fi os.FileInfo, err error) error { if err != nil { fmt.Println(err) return nil } if fi.IsDir() { return nil } matched, err := filepath.Match("*.mp3", fi.Name()) if err != nil { fmt.Println(err) return err } if matched { fmt.Println(fp) } return nil } func main() { filepath.Walk("/", VisitFile) }
Preserve the algorithm and functionality while converting the code from Ruby to C.
require 'find' Find.find('/your/path') do |f| puts f if f.match(/\.mp3\Z/) end
#include <sys/types.h> #include <sys/stat.h> #include <unistd.h> #include <dirent.h> #include <regex.h> #include <stdio.h> #include <string.h> #include <errno.h> #include <err.h> enum { WALK_OK = 0, WALK_BADPATTERN, WALK_NAMETOOLONG, WALK_BADIO, }; #define WS_NONE 0 #define WS_RECURSIVE (1 << 0) #define WS_DEFAULT WS_RECURSIVE #define WS_FOLLOWLINK (1 << 1) #define WS_DOTFILES (1 << 2) #define WS_MATCHDIRS (1 << 3) int walk_recur(char *dname, regex_t *reg, int spec) { struct dirent *dent; DIR *dir; struct stat st; char fn[FILENAME_MAX]; int res = WALK_OK; int len = strlen(dname); if (len >= FILENAME_MAX - 1) return WALK_NAMETOOLONG; strcpy(fn, dname); fn[len++] = '/'; if (!(dir = opendir(dname))) { warn("can't open %s", dname); return WALK_BADIO; } errno = 0; while ((dent = readdir(dir))) { if (!(spec & WS_DOTFILES) && dent->d_name[0] == '.') continue; if (!strcmp(dent->d_name, ".") || !strcmp(dent->d_name, "..")) continue; strncpy(fn + len, dent->d_name, FILENAME_MAX - len); if (lstat(fn, &st) == -1) { warn("Can't stat %s", fn); res = WALK_BADIO; continue; } if (S_ISLNK(st.st_mode) && !(spec & WS_FOLLOWLINK)) continue; if (S_ISDIR(st.st_mode)) { if ((spec & WS_RECURSIVE)) walk_recur(fn, reg, spec); if (!(spec & WS_MATCHDIRS)) continue; } if (!regexec(reg, fn, 0, 0, 0)) puts(fn); } if (dir) closedir(dir); return res ? res : errno ? WALK_BADIO : WALK_OK; } int walk_dir(char *dname, char *pattern, int spec) { regex_t r; int res; if (regcomp(&r, pattern, REG_EXTENDED | REG_NOSUB)) return WALK_BADPATTERN; res = walk_recur(dname, &r, spec); regfree(&r); return res; } int main() { int r = walk_dir(".", ".\\.c$", WS_DEFAULT|WS_MATCHDIRS); switch(r) { case WALK_OK: break; case WALK_BADIO: err(1, "IO error"); case WALK_BADPATTERN: err(1, "Bad pattern"); case WALK_NAMETOOLONG: err(1, "Filename too long"); default: err(1, "Unknown error?"); } return 0; }
Can you help me rewrite this code in C# instead of Ruby, keeping it the same logically?
require 'find' Find.find('/your/path') do |f| puts f if f.match(/\.mp3\Z/) end
using System; using System.Collections.Generic; using System.IO; using System.Linq; namespace RosettaRecursiveDirectory { class Program { static IEnumerable<FileInfo> TraverseDirectory(string rootPath, Func<FileInfo, bool> Pattern) { var directoryStack = new Stack<DirectoryInfo>(); directoryStack.Push(new DirectoryInfo(rootPath)); while (directoryStack.Count > 0) { var dir = directoryStack.Pop(); try { foreach (var i in dir.GetDirectories()) directoryStack.Push(i); } catch (UnauthorizedAccessException) { continue; } foreach (var f in dir.GetFiles().Where(Pattern)) yield return f; } } static void Main(string[] args) { foreach (var file in TraverseDirectory(@"C:\Windows", f => f.Extension == ".wmv")) Console.WriteLine(file.FullName); Console.WriteLine("Done."); } } }
Generate a C++ translation of this Ruby snippet without changing its computational steps.
require 'find' Find.find('/your/path') do |f| puts f if f.match(/\.mp3\Z/) end
#include "boost/filesystem.hpp" #include "boost/regex.hpp" #include <iostream> using namespace boost::filesystem; int main() { path current_dir("."); boost::regex pattern("a.*"); for (recursive_directory_iterator iter(current_dir), end; iter != end; ++iter) { std::string name = iter->path().filename().string(); if (regex_match(name, pattern)) std::cout << iter->path() << "\n"; } }
Please provide an equivalent version of this Ruby code in Java.
require 'find' Find.find('/your/path') do |f| puts f if f.match(/\.mp3\Z/) end
import java.io.File; public class MainEntry { public static void main(String[] args) { walkin(new File("/home/user")); } public static void walkin(File dir) { String pattern = ".mp3"; File listFile[] = dir.listFiles(); if (listFile != null) { for (int i=0; i<listFile.length; i++) { if (listFile[i].isDirectory()) { walkin(listFile[i]); } else { if (listFile[i].getName().endsWith(pattern)) { System.out.println(listFile[i].getPath()); } } } } } }
Transform the following Ruby implementation into Python, maintaining the same output and logic.
require 'find' Find.find('/your/path') do |f| puts f if f.match(/\.mp3\Z/) end
from pathlib import Path for path in Path('.').rglob('*.*'): print(path)
Can you help me rewrite this code in VB instead of Ruby, keeping it the same logically?
require 'find' Find.find('/your/path') do |f| puts f if f.match(/\.mp3\Z/) end
Sub printFiles(parentDir As FolderItem, pattern As String) For i As Integer = 1 To parentDir.Count If parentDir.Item(i).Directory Then printFiles(parentDir.Item(i), pattern) Else Dim rg as New RegEx Dim myMatch as RegExMatch rg.SearchPattern = pattern myMatch = rg.search(parentDir.Item(i).Name) If myMatch <> Nil Then Print(parentDir.Item(i).AbsolutePath) End If Next End Sub
Can you help me rewrite this code in Go instead of Ruby, keeping it the same logically?
require 'find' Find.find('/your/path') do |f| puts f if f.match(/\.mp3\Z/) end
package main import ( "fmt" "os" "path/filepath" ) func VisitFile(fp string, fi os.FileInfo, err error) error { if err != nil { fmt.Println(err) return nil } if fi.IsDir() { return nil } matched, err := filepath.Match("*.mp3", fi.Name()) if err != nil { fmt.Println(err) return err } if matched { fmt.Println(fp) } return nil } func main() { filepath.Walk("/", VisitFile) }
Generate an equivalent C version of this Scala code.
import java.io.File fun walkDirectoryRecursively(dirPath: String, pattern: Regex): Sequence<String> { val d = File(dirPath) require (d.exists() && d.isDirectory()) return d.walk().map { it.name }.filter { it.matches(pattern) }.sorted().distinct() } fun main(args: Array<String>) { val r = Regex("""^v(a|f).*\.h$""") val files = walkDirectoryRecursively("/usr/include", r) for (file in files) println(file) }
#include <sys/types.h> #include <sys/stat.h> #include <unistd.h> #include <dirent.h> #include <regex.h> #include <stdio.h> #include <string.h> #include <errno.h> #include <err.h> enum { WALK_OK = 0, WALK_BADPATTERN, WALK_NAMETOOLONG, WALK_BADIO, }; #define WS_NONE 0 #define WS_RECURSIVE (1 << 0) #define WS_DEFAULT WS_RECURSIVE #define WS_FOLLOWLINK (1 << 1) #define WS_DOTFILES (1 << 2) #define WS_MATCHDIRS (1 << 3) int walk_recur(char *dname, regex_t *reg, int spec) { struct dirent *dent; DIR *dir; struct stat st; char fn[FILENAME_MAX]; int res = WALK_OK; int len = strlen(dname); if (len >= FILENAME_MAX - 1) return WALK_NAMETOOLONG; strcpy(fn, dname); fn[len++] = '/'; if (!(dir = opendir(dname))) { warn("can't open %s", dname); return WALK_BADIO; } errno = 0; while ((dent = readdir(dir))) { if (!(spec & WS_DOTFILES) && dent->d_name[0] == '.') continue; if (!strcmp(dent->d_name, ".") || !strcmp(dent->d_name, "..")) continue; strncpy(fn + len, dent->d_name, FILENAME_MAX - len); if (lstat(fn, &st) == -1) { warn("Can't stat %s", fn); res = WALK_BADIO; continue; } if (S_ISLNK(st.st_mode) && !(spec & WS_FOLLOWLINK)) continue; if (S_ISDIR(st.st_mode)) { if ((spec & WS_RECURSIVE)) walk_recur(fn, reg, spec); if (!(spec & WS_MATCHDIRS)) continue; } if (!regexec(reg, fn, 0, 0, 0)) puts(fn); } if (dir) closedir(dir); return res ? res : errno ? WALK_BADIO : WALK_OK; } int walk_dir(char *dname, char *pattern, int spec) { regex_t r; int res; if (regcomp(&r, pattern, REG_EXTENDED | REG_NOSUB)) return WALK_BADPATTERN; res = walk_recur(dname, &r, spec); regfree(&r); return res; } int main() { int r = walk_dir(".", ".\\.c$", WS_DEFAULT|WS_MATCHDIRS); switch(r) { case WALK_OK: break; case WALK_BADIO: err(1, "IO error"); case WALK_BADPATTERN: err(1, "Bad pattern"); case WALK_NAMETOOLONG: err(1, "Filename too long"); default: err(1, "Unknown error?"); } return 0; }
Generate an equivalent C# version of this Scala code.
import java.io.File fun walkDirectoryRecursively(dirPath: String, pattern: Regex): Sequence<String> { val d = File(dirPath) require (d.exists() && d.isDirectory()) return d.walk().map { it.name }.filter { it.matches(pattern) }.sorted().distinct() } fun main(args: Array<String>) { val r = Regex("""^v(a|f).*\.h$""") val files = walkDirectoryRecursively("/usr/include", r) for (file in files) println(file) }
using System; using System.Collections.Generic; using System.IO; using System.Linq; namespace RosettaRecursiveDirectory { class Program { static IEnumerable<FileInfo> TraverseDirectory(string rootPath, Func<FileInfo, bool> Pattern) { var directoryStack = new Stack<DirectoryInfo>(); directoryStack.Push(new DirectoryInfo(rootPath)); while (directoryStack.Count > 0) { var dir = directoryStack.Pop(); try { foreach (var i in dir.GetDirectories()) directoryStack.Push(i); } catch (UnauthorizedAccessException) { continue; } foreach (var f in dir.GetFiles().Where(Pattern)) yield return f; } } static void Main(string[] args) { foreach (var file in TraverseDirectory(@"C:\Windows", f => f.Extension == ".wmv")) Console.WriteLine(file.FullName); Console.WriteLine("Done."); } } }
Convert the following code from Scala to C++, ensuring the logic remains intact.
import java.io.File fun walkDirectoryRecursively(dirPath: String, pattern: Regex): Sequence<String> { val d = File(dirPath) require (d.exists() && d.isDirectory()) return d.walk().map { it.name }.filter { it.matches(pattern) }.sorted().distinct() } fun main(args: Array<String>) { val r = Regex("""^v(a|f).*\.h$""") val files = walkDirectoryRecursively("/usr/include", r) for (file in files) println(file) }
#include "boost/filesystem.hpp" #include "boost/regex.hpp" #include <iostream> using namespace boost::filesystem; int main() { path current_dir("."); boost::regex pattern("a.*"); for (recursive_directory_iterator iter(current_dir), end; iter != end; ++iter) { std::string name = iter->path().filename().string(); if (regex_match(name, pattern)) std::cout << iter->path() << "\n"; } }
Maintain the same structure and functionality when rewriting this code in Java.
import java.io.File fun walkDirectoryRecursively(dirPath: String, pattern: Regex): Sequence<String> { val d = File(dirPath) require (d.exists() && d.isDirectory()) return d.walk().map { it.name }.filter { it.matches(pattern) }.sorted().distinct() } fun main(args: Array<String>) { val r = Regex("""^v(a|f).*\.h$""") val files = walkDirectoryRecursively("/usr/include", r) for (file in files) println(file) }
import java.io.File; public class MainEntry { public static void main(String[] args) { walkin(new File("/home/user")); } public static void walkin(File dir) { String pattern = ".mp3"; File listFile[] = dir.listFiles(); if (listFile != null) { for (int i=0; i<listFile.length; i++) { if (listFile[i].isDirectory()) { walkin(listFile[i]); } else { if (listFile[i].getName().endsWith(pattern)) { System.out.println(listFile[i].getPath()); } } } } } }
Ensure the translated Python code behaves exactly like the original Scala snippet.
import java.io.File fun walkDirectoryRecursively(dirPath: String, pattern: Regex): Sequence<String> { val d = File(dirPath) require (d.exists() && d.isDirectory()) return d.walk().map { it.name }.filter { it.matches(pattern) }.sorted().distinct() } fun main(args: Array<String>) { val r = Regex("""^v(a|f).*\.h$""") val files = walkDirectoryRecursively("/usr/include", r) for (file in files) println(file) }
from pathlib import Path for path in Path('.').rglob('*.*'): print(path)
Port the provided Scala code into VB while preserving the original functionality.
import java.io.File fun walkDirectoryRecursively(dirPath: String, pattern: Regex): Sequence<String> { val d = File(dirPath) require (d.exists() && d.isDirectory()) return d.walk().map { it.name }.filter { it.matches(pattern) }.sorted().distinct() } fun main(args: Array<String>) { val r = Regex("""^v(a|f).*\.h$""") val files = walkDirectoryRecursively("/usr/include", r) for (file in files) println(file) }
Sub printFiles(parentDir As FolderItem, pattern As String) For i As Integer = 1 To parentDir.Count If parentDir.Item(i).Directory Then printFiles(parentDir.Item(i), pattern) Else Dim rg as New RegEx Dim myMatch as RegExMatch rg.SearchPattern = pattern myMatch = rg.search(parentDir.Item(i).Name) If myMatch <> Nil Then Print(parentDir.Item(i).AbsolutePath) End If Next End Sub
Maintain the same structure and functionality when rewriting this code in Go.
import java.io.File fun walkDirectoryRecursively(dirPath: String, pattern: Regex): Sequence<String> { val d = File(dirPath) require (d.exists() && d.isDirectory()) return d.walk().map { it.name }.filter { it.matches(pattern) }.sorted().distinct() } fun main(args: Array<String>) { val r = Regex("""^v(a|f).*\.h$""") val files = walkDirectoryRecursively("/usr/include", r) for (file in files) println(file) }
package main import ( "fmt" "os" "path/filepath" ) func VisitFile(fp string, fi os.FileInfo, err error) error { if err != nil { fmt.Println(err) return nil } if fi.IsDir() { return nil } matched, err := filepath.Match("*.mp3", fi.Name()) if err != nil { fmt.Println(err) return err } if matched { fmt.Println(fp) } return nil } func main() { filepath.Walk("/", VisitFile) }
Produce a functionally identical C code for the snippet given in Swift.
import Foundation let fileSystem = FileManager.default let rootPath = "/" if let fsTree = fileSystem.enumerator(atPath: rootPath) { while let fsNodeName = fsTree.nextObject() as? NSString { let fullPath = "\(rootPath)/\(fsNodeName)" var isDir: ObjCBool = false fileSystem.fileExists(atPath: fullPath, isDirectory: &isDir) if !isDir.boolValue && fsNodeName.pathExtension == "txt" { print(fsNodeName) } } }
#include <sys/types.h> #include <sys/stat.h> #include <unistd.h> #include <dirent.h> #include <regex.h> #include <stdio.h> #include <string.h> #include <errno.h> #include <err.h> enum { WALK_OK = 0, WALK_BADPATTERN, WALK_NAMETOOLONG, WALK_BADIO, }; #define WS_NONE 0 #define WS_RECURSIVE (1 << 0) #define WS_DEFAULT WS_RECURSIVE #define WS_FOLLOWLINK (1 << 1) #define WS_DOTFILES (1 << 2) #define WS_MATCHDIRS (1 << 3) int walk_recur(char *dname, regex_t *reg, int spec) { struct dirent *dent; DIR *dir; struct stat st; char fn[FILENAME_MAX]; int res = WALK_OK; int len = strlen(dname); if (len >= FILENAME_MAX - 1) return WALK_NAMETOOLONG; strcpy(fn, dname); fn[len++] = '/'; if (!(dir = opendir(dname))) { warn("can't open %s", dname); return WALK_BADIO; } errno = 0; while ((dent = readdir(dir))) { if (!(spec & WS_DOTFILES) && dent->d_name[0] == '.') continue; if (!strcmp(dent->d_name, ".") || !strcmp(dent->d_name, "..")) continue; strncpy(fn + len, dent->d_name, FILENAME_MAX - len); if (lstat(fn, &st) == -1) { warn("Can't stat %s", fn); res = WALK_BADIO; continue; } if (S_ISLNK(st.st_mode) && !(spec & WS_FOLLOWLINK)) continue; if (S_ISDIR(st.st_mode)) { if ((spec & WS_RECURSIVE)) walk_recur(fn, reg, spec); if (!(spec & WS_MATCHDIRS)) continue; } if (!regexec(reg, fn, 0, 0, 0)) puts(fn); } if (dir) closedir(dir); return res ? res : errno ? WALK_BADIO : WALK_OK; } int walk_dir(char *dname, char *pattern, int spec) { regex_t r; int res; if (regcomp(&r, pattern, REG_EXTENDED | REG_NOSUB)) return WALK_BADPATTERN; res = walk_recur(dname, &r, spec); regfree(&r); return res; } int main() { int r = walk_dir(".", ".\\.c$", WS_DEFAULT|WS_MATCHDIRS); switch(r) { case WALK_OK: break; case WALK_BADIO: err(1, "IO error"); case WALK_BADPATTERN: err(1, "Bad pattern"); case WALK_NAMETOOLONG: err(1, "Filename too long"); default: err(1, "Unknown error?"); } return 0; }
Convert this Swift snippet to C# and keep its semantics consistent.
import Foundation let fileSystem = FileManager.default let rootPath = "/" if let fsTree = fileSystem.enumerator(atPath: rootPath) { while let fsNodeName = fsTree.nextObject() as? NSString { let fullPath = "\(rootPath)/\(fsNodeName)" var isDir: ObjCBool = false fileSystem.fileExists(atPath: fullPath, isDirectory: &isDir) if !isDir.boolValue && fsNodeName.pathExtension == "txt" { print(fsNodeName) } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; namespace RosettaRecursiveDirectory { class Program { static IEnumerable<FileInfo> TraverseDirectory(string rootPath, Func<FileInfo, bool> Pattern) { var directoryStack = new Stack<DirectoryInfo>(); directoryStack.Push(new DirectoryInfo(rootPath)); while (directoryStack.Count > 0) { var dir = directoryStack.Pop(); try { foreach (var i in dir.GetDirectories()) directoryStack.Push(i); } catch (UnauthorizedAccessException) { continue; } foreach (var f in dir.GetFiles().Where(Pattern)) yield return f; } } static void Main(string[] args) { foreach (var file in TraverseDirectory(@"C:\Windows", f => f.Extension == ".wmv")) Console.WriteLine(file.FullName); Console.WriteLine("Done."); } } }
Please provide an equivalent version of this Swift code in C++.
import Foundation let fileSystem = FileManager.default let rootPath = "/" if let fsTree = fileSystem.enumerator(atPath: rootPath) { while let fsNodeName = fsTree.nextObject() as? NSString { let fullPath = "\(rootPath)/\(fsNodeName)" var isDir: ObjCBool = false fileSystem.fileExists(atPath: fullPath, isDirectory: &isDir) if !isDir.boolValue && fsNodeName.pathExtension == "txt" { print(fsNodeName) } } }
#include "boost/filesystem.hpp" #include "boost/regex.hpp" #include <iostream> using namespace boost::filesystem; int main() { path current_dir("."); boost::regex pattern("a.*"); for (recursive_directory_iterator iter(current_dir), end; iter != end; ++iter) { std::string name = iter->path().filename().string(); if (regex_match(name, pattern)) std::cout << iter->path() << "\n"; } }
Translate this program into Java but keep the logic exactly as in Swift.
import Foundation let fileSystem = FileManager.default let rootPath = "/" if let fsTree = fileSystem.enumerator(atPath: rootPath) { while let fsNodeName = fsTree.nextObject() as? NSString { let fullPath = "\(rootPath)/\(fsNodeName)" var isDir: ObjCBool = false fileSystem.fileExists(atPath: fullPath, isDirectory: &isDir) if !isDir.boolValue && fsNodeName.pathExtension == "txt" { print(fsNodeName) } } }
import java.io.File; public class MainEntry { public static void main(String[] args) { walkin(new File("/home/user")); } public static void walkin(File dir) { String pattern = ".mp3"; File listFile[] = dir.listFiles(); if (listFile != null) { for (int i=0; i<listFile.length; i++) { if (listFile[i].isDirectory()) { walkin(listFile[i]); } else { if (listFile[i].getName().endsWith(pattern)) { System.out.println(listFile[i].getPath()); } } } } } }
Change the programming language of this snippet from Swift to Python without modifying what it does.
import Foundation let fileSystem = FileManager.default let rootPath = "/" if let fsTree = fileSystem.enumerator(atPath: rootPath) { while let fsNodeName = fsTree.nextObject() as? NSString { let fullPath = "\(rootPath)/\(fsNodeName)" var isDir: ObjCBool = false fileSystem.fileExists(atPath: fullPath, isDirectory: &isDir) if !isDir.boolValue && fsNodeName.pathExtension == "txt" { print(fsNodeName) } } }
from pathlib import Path for path in Path('.').rglob('*.*'): print(path)
Produce a functionally identical VB code for the snippet given in Swift.
import Foundation let fileSystem = FileManager.default let rootPath = "/" if let fsTree = fileSystem.enumerator(atPath: rootPath) { while let fsNodeName = fsTree.nextObject() as? NSString { let fullPath = "\(rootPath)/\(fsNodeName)" var isDir: ObjCBool = false fileSystem.fileExists(atPath: fullPath, isDirectory: &isDir) if !isDir.boolValue && fsNodeName.pathExtension == "txt" { print(fsNodeName) } } }
Sub printFiles(parentDir As FolderItem, pattern As String) For i As Integer = 1 To parentDir.Count If parentDir.Item(i).Directory Then printFiles(parentDir.Item(i), pattern) Else Dim rg as New RegEx Dim myMatch as RegExMatch rg.SearchPattern = pattern myMatch = rg.search(parentDir.Item(i).Name) If myMatch <> Nil Then Print(parentDir.Item(i).AbsolutePath) End If Next End Sub
Change the following Swift code into Go without altering its purpose.
import Foundation let fileSystem = FileManager.default let rootPath = "/" if let fsTree = fileSystem.enumerator(atPath: rootPath) { while let fsNodeName = fsTree.nextObject() as? NSString { let fullPath = "\(rootPath)/\(fsNodeName)" var isDir: ObjCBool = false fileSystem.fileExists(atPath: fullPath, isDirectory: &isDir) if !isDir.boolValue && fsNodeName.pathExtension == "txt" { print(fsNodeName) } } }
package main import ( "fmt" "os" "path/filepath" ) func VisitFile(fp string, fi os.FileInfo, err error) error { if err != nil { fmt.Println(err) return nil } if fi.IsDir() { return nil } matched, err := filepath.Match("*.mp3", fi.Name()) if err != nil { fmt.Println(err) return err } if matched { fmt.Println(fp) } return nil } func main() { filepath.Walk("/", VisitFile) }
Rewrite this program in C while keeping its functionality equivalent to the Tcl version.
package require fileutil proc walkin {path cmd} { set normalized [::fileutil::fullnormalize $path] set myname [lindex [info level 0] 0] set children [glob -nocomplain -directory $path -types hidden *] lappend children {*}[glob -nocomplain -directory $path *] foreach child $children[set children {}] { if {[file tail $child] in {. ..}} { continue } if {[file isdirectory $child]} { if {[file type $child] eq "link"} { set normalizedchild [fileutil::fullnormalize $child] if {[string first $normalized/ $normalizedchild] == 0} { } else { $myname $child $cmd } } } {*}$cmd $child } } walkin /home/usr {apply {fname { set tail [file tail $fname] if {[string match *.mp3 $tail]} { puts $fname } }}}
#include <sys/types.h> #include <sys/stat.h> #include <unistd.h> #include <dirent.h> #include <regex.h> #include <stdio.h> #include <string.h> #include <errno.h> #include <err.h> enum { WALK_OK = 0, WALK_BADPATTERN, WALK_NAMETOOLONG, WALK_BADIO, }; #define WS_NONE 0 #define WS_RECURSIVE (1 << 0) #define WS_DEFAULT WS_RECURSIVE #define WS_FOLLOWLINK (1 << 1) #define WS_DOTFILES (1 << 2) #define WS_MATCHDIRS (1 << 3) int walk_recur(char *dname, regex_t *reg, int spec) { struct dirent *dent; DIR *dir; struct stat st; char fn[FILENAME_MAX]; int res = WALK_OK; int len = strlen(dname); if (len >= FILENAME_MAX - 1) return WALK_NAMETOOLONG; strcpy(fn, dname); fn[len++] = '/'; if (!(dir = opendir(dname))) { warn("can't open %s", dname); return WALK_BADIO; } errno = 0; while ((dent = readdir(dir))) { if (!(spec & WS_DOTFILES) && dent->d_name[0] == '.') continue; if (!strcmp(dent->d_name, ".") || !strcmp(dent->d_name, "..")) continue; strncpy(fn + len, dent->d_name, FILENAME_MAX - len); if (lstat(fn, &st) == -1) { warn("Can't stat %s", fn); res = WALK_BADIO; continue; } if (S_ISLNK(st.st_mode) && !(spec & WS_FOLLOWLINK)) continue; if (S_ISDIR(st.st_mode)) { if ((spec & WS_RECURSIVE)) walk_recur(fn, reg, spec); if (!(spec & WS_MATCHDIRS)) continue; } if (!regexec(reg, fn, 0, 0, 0)) puts(fn); } if (dir) closedir(dir); return res ? res : errno ? WALK_BADIO : WALK_OK; } int walk_dir(char *dname, char *pattern, int spec) { regex_t r; int res; if (regcomp(&r, pattern, REG_EXTENDED | REG_NOSUB)) return WALK_BADPATTERN; res = walk_recur(dname, &r, spec); regfree(&r); return res; } int main() { int r = walk_dir(".", ".\\.c$", WS_DEFAULT|WS_MATCHDIRS); switch(r) { case WALK_OK: break; case WALK_BADIO: err(1, "IO error"); case WALK_BADPATTERN: err(1, "Bad pattern"); case WALK_NAMETOOLONG: err(1, "Filename too long"); default: err(1, "Unknown error?"); } return 0; }
Translate this program into C# but keep the logic exactly as in Tcl.
package require fileutil proc walkin {path cmd} { set normalized [::fileutil::fullnormalize $path] set myname [lindex [info level 0] 0] set children [glob -nocomplain -directory $path -types hidden *] lappend children {*}[glob -nocomplain -directory $path *] foreach child $children[set children {}] { if {[file tail $child] in {. ..}} { continue } if {[file isdirectory $child]} { if {[file type $child] eq "link"} { set normalizedchild [fileutil::fullnormalize $child] if {[string first $normalized/ $normalizedchild] == 0} { } else { $myname $child $cmd } } } {*}$cmd $child } } walkin /home/usr {apply {fname { set tail [file tail $fname] if {[string match *.mp3 $tail]} { puts $fname } }}}
using System; using System.Collections.Generic; using System.IO; using System.Linq; namespace RosettaRecursiveDirectory { class Program { static IEnumerable<FileInfo> TraverseDirectory(string rootPath, Func<FileInfo, bool> Pattern) { var directoryStack = new Stack<DirectoryInfo>(); directoryStack.Push(new DirectoryInfo(rootPath)); while (directoryStack.Count > 0) { var dir = directoryStack.Pop(); try { foreach (var i in dir.GetDirectories()) directoryStack.Push(i); } catch (UnauthorizedAccessException) { continue; } foreach (var f in dir.GetFiles().Where(Pattern)) yield return f; } } static void Main(string[] args) { foreach (var file in TraverseDirectory(@"C:\Windows", f => f.Extension == ".wmv")) Console.WriteLine(file.FullName); Console.WriteLine("Done."); } } }
Please provide an equivalent version of this Tcl code in C++.
package require fileutil proc walkin {path cmd} { set normalized [::fileutil::fullnormalize $path] set myname [lindex [info level 0] 0] set children [glob -nocomplain -directory $path -types hidden *] lappend children {*}[glob -nocomplain -directory $path *] foreach child $children[set children {}] { if {[file tail $child] in {. ..}} { continue } if {[file isdirectory $child]} { if {[file type $child] eq "link"} { set normalizedchild [fileutil::fullnormalize $child] if {[string first $normalized/ $normalizedchild] == 0} { } else { $myname $child $cmd } } } {*}$cmd $child } } walkin /home/usr {apply {fname { set tail [file tail $fname] if {[string match *.mp3 $tail]} { puts $fname } }}}
#include "boost/filesystem.hpp" #include "boost/regex.hpp" #include <iostream> using namespace boost::filesystem; int main() { path current_dir("."); boost::regex pattern("a.*"); for (recursive_directory_iterator iter(current_dir), end; iter != end; ++iter) { std::string name = iter->path().filename().string(); if (regex_match(name, pattern)) std::cout << iter->path() << "\n"; } }
Can you help me rewrite this code in Java instead of Tcl, keeping it the same logically?
package require fileutil proc walkin {path cmd} { set normalized [::fileutil::fullnormalize $path] set myname [lindex [info level 0] 0] set children [glob -nocomplain -directory $path -types hidden *] lappend children {*}[glob -nocomplain -directory $path *] foreach child $children[set children {}] { if {[file tail $child] in {. ..}} { continue } if {[file isdirectory $child]} { if {[file type $child] eq "link"} { set normalizedchild [fileutil::fullnormalize $child] if {[string first $normalized/ $normalizedchild] == 0} { } else { $myname $child $cmd } } } {*}$cmd $child } } walkin /home/usr {apply {fname { set tail [file tail $fname] if {[string match *.mp3 $tail]} { puts $fname } }}}
import java.io.File; public class MainEntry { public static void main(String[] args) { walkin(new File("/home/user")); } public static void walkin(File dir) { String pattern = ".mp3"; File listFile[] = dir.listFiles(); if (listFile != null) { for (int i=0; i<listFile.length; i++) { if (listFile[i].isDirectory()) { walkin(listFile[i]); } else { if (listFile[i].getName().endsWith(pattern)) { System.out.println(listFile[i].getPath()); } } } } } }
Write a version of this Tcl function in Python with identical behavior.
package require fileutil proc walkin {path cmd} { set normalized [::fileutil::fullnormalize $path] set myname [lindex [info level 0] 0] set children [glob -nocomplain -directory $path -types hidden *] lappend children {*}[glob -nocomplain -directory $path *] foreach child $children[set children {}] { if {[file tail $child] in {. ..}} { continue } if {[file isdirectory $child]} { if {[file type $child] eq "link"} { set normalizedchild [fileutil::fullnormalize $child] if {[string first $normalized/ $normalizedchild] == 0} { } else { $myname $child $cmd } } } {*}$cmd $child } } walkin /home/usr {apply {fname { set tail [file tail $fname] if {[string match *.mp3 $tail]} { puts $fname } }}}
from pathlib import Path for path in Path('.').rglob('*.*'): print(path)
Change the following Tcl code into VB without altering its purpose.
package require fileutil proc walkin {path cmd} { set normalized [::fileutil::fullnormalize $path] set myname [lindex [info level 0] 0] set children [glob -nocomplain -directory $path -types hidden *] lappend children {*}[glob -nocomplain -directory $path *] foreach child $children[set children {}] { if {[file tail $child] in {. ..}} { continue } if {[file isdirectory $child]} { if {[file type $child] eq "link"} { set normalizedchild [fileutil::fullnormalize $child] if {[string first $normalized/ $normalizedchild] == 0} { } else { $myname $child $cmd } } } {*}$cmd $child } } walkin /home/usr {apply {fname { set tail [file tail $fname] if {[string match *.mp3 $tail]} { puts $fname } }}}
Sub printFiles(parentDir As FolderItem, pattern As String) For i As Integer = 1 To parentDir.Count If parentDir.Item(i).Directory Then printFiles(parentDir.Item(i), pattern) Else Dim rg as New RegEx Dim myMatch as RegExMatch rg.SearchPattern = pattern myMatch = rg.search(parentDir.Item(i).Name) If myMatch <> Nil Then Print(parentDir.Item(i).AbsolutePath) End If Next End Sub
Produce a language-to-language conversion: from Tcl to Go, same semantics.
package require fileutil proc walkin {path cmd} { set normalized [::fileutil::fullnormalize $path] set myname [lindex [info level 0] 0] set children [glob -nocomplain -directory $path -types hidden *] lappend children {*}[glob -nocomplain -directory $path *] foreach child $children[set children {}] { if {[file tail $child] in {. ..}} { continue } if {[file isdirectory $child]} { if {[file type $child] eq "link"} { set normalizedchild [fileutil::fullnormalize $child] if {[string first $normalized/ $normalizedchild] == 0} { } else { $myname $child $cmd } } } {*}$cmd $child } } walkin /home/usr {apply {fname { set tail [file tail $fname] if {[string match *.mp3 $tail]} { puts $fname } }}}
package main import ( "fmt" "os" "path/filepath" ) func VisitFile(fp string, fi os.FileInfo, err error) error { if err != nil { fmt.Println(err) return nil } if fi.IsDir() { return nil } matched, err := filepath.Match("*.mp3", fi.Name()) if err != nil { fmt.Println(err) return err } if matched { fmt.Println(fp) } return nil } func main() { filepath.Walk("/", VisitFile) }
Write the same code in PHP as shown below in Rust.
#![feature(fs_walk)] use std::fs; use std::path::Path; fn main() { for f in fs::walk_dir(&Path::new("/home/pavel/Music")).unwrap() { let p = f.unwrap().path(); if p.extension().unwrap_or("".as_ref()) == "mp3" { println!("{:?}", p); } } }
function findFiles($dir = '.', $pattern = '/./'){ $prefix = $dir . '/'; $dir = dir($dir); while (false !== ($file = $dir->read())){ if ($file === '.' || $file === '..') continue; $file = $prefix . $file; if (is_dir($file)) findFiles($file, $pattern); if (preg_match($pattern, $file)){ echo $file . "\n"; } } } findFiles('./foo', '/\.bar$/');
Please provide an equivalent version of this Ada code in PHP.
with Ada.Directories; use Ada.Directories; with Ada.Text_IO; procedure Test_Directory_Walk is procedure Walk (Name : String; Pattern : String) is procedure Print (Item : Directory_Entry_Type) is begin Ada.Text_IO.Put_Line (Full_Name (Item)); end Print; procedure Walk (Item : Directory_Entry_Type) is begin if Simple_Name (Item) /= "." and then Simple_Name (Item) /= ".." then Walk (Full_Name (Item), Pattern); end if; exception when Name_Error => null; end Walk; begin Search (Name, Pattern, (others => True), Print'Access); Search (Name, "", (Directory => True, others => False), Walk'Access); end Walk; begin Walk (".", "*.adb"); end Test_Directory_Walk;
function findFiles($dir = '.', $pattern = '/./'){ $prefix = $dir . '/'; $dir = dir($dir); while (false !== ($file = $dir->read())){ if ($file === '.' || $file === '..') continue; $file = $prefix . $file; if (is_dir($file)) findFiles($file, $pattern); if (preg_match($pattern, $file)){ echo $file . "\n"; } } } findFiles('./foo', '/\.bar$/');
Can you help me rewrite this code in PHP instead of Arturo, keeping it the same logically?
print list.recursive "." select list.recursive "some/path" => [".md" = extract.extension] select list.recursive "some/path" => [in? "test"]
function findFiles($dir = '.', $pattern = '/./'){ $prefix = $dir . '/'; $dir = dir($dir); while (false !== ($file = $dir->read())){ if ($file === '.' || $file === '..') continue; $file = $prefix . $file; if (is_dir($file)) findFiles($file, $pattern); if (preg_match($pattern, $file)){ echo $file . "\n"; } } } findFiles('./foo', '/\.bar$/');
Rewrite this program in PHP while keeping its functionality equivalent to the AutoHotKey version.
Loop, %A_Temp%\*.tmp,,1 out .= A_LoopFileName "`n" MsgBox,% out
function findFiles($dir = '.', $pattern = '/./'){ $prefix = $dir . '/'; $dir = dir($dir); while (false !== ($file = $dir->read())){ if ($file === '.' || $file === '..') continue; $file = $prefix . $file; if (is_dir($file)) findFiles($file, $pattern); if (preg_match($pattern, $file)){ echo $file . "\n"; } } } findFiles('./foo', '/\.bar$/');
Can you help me rewrite this code in PHP instead of BBC_Basic, keeping it the same logically?
directory$ = "C:\Windows\" pattern$ = "*.chm" PROClisttree(directory$, pattern$) END DEF PROClisttree(dir$, filter$) LOCAL dir%, sh%, res% DIM dir% LOCAL 317 IF RIGHT$(dir$) <> "\" IF RIGHT$(dir$) <> "/" dir$ += "\" SYS "FindFirstFile", dir$ + filter$, dir% TO sh% IF sh% <> -1 THEN REPEAT IF (!dir% AND 16) = 0 PRINT dir$ + $$(dir%+44) SYS "FindNextFile", sh%, dir% TO res% UNTIL res% = 0 SYS "FindClose", sh% ENDIF SYS "FindFirstFile", dir$ + "*", dir% TO sh% IF sh% <> -1 THEN REPEAT IF (!dir% AND 16) IF dir%?44 <> &2E THEN PROClisttree(dir$ + $$(dir%+44) + "\", filter$) ENDIF SYS "FindNextFile", sh%, dir% TO res% UNTIL res% = 0 SYS "FindClose", sh% ENDIF ENDPROC
function findFiles($dir = '.', $pattern = '/./'){ $prefix = $dir . '/'; $dir = dir($dir); while (false !== ($file = $dir->read())){ if ($file === '.' || $file === '..') continue; $file = $prefix . $file; if (is_dir($file)) findFiles($file, $pattern); if (preg_match($pattern, $file)){ echo $file . "\n"; } } } findFiles('./foo', '/\.bar$/');
Generate an equivalent PHP version of this Clojure code.
(use '[clojure.java.io]) (defn walk [dirpath pattern] (doall (filter #(re-matches pattern (.getName %)) (file-seq (file dirpath))))) (map #(println (.getPath %)) (walk "src" #".*\.clj"))
function findFiles($dir = '.', $pattern = '/./'){ $prefix = $dir . '/'; $dir = dir($dir); while (false !== ($file = $dir->read())){ if ($file === '.' || $file === '..') continue; $file = $prefix . $file; if (is_dir($file)) findFiles($file, $pattern); if (preg_match($pattern, $file)){ echo $file . "\n"; } } } findFiles('./foo', '/\.bar$/');
Please provide an equivalent version of this Common_Lisp code in PHP.
(ql:quickload :cl-fad) (defun mapc-directory-tree (fn directory &key (depth-first-p t)) (dolist (entry (cl-fad:list-directory directory)) (unless depth-first-p (funcall fn entry)) (when (cl-fad:directory-pathname-p entry) (mapc-directory-tree fn entry)) (when depth-first-p (funcall fn entry))))
function findFiles($dir = '.', $pattern = '/./'){ $prefix = $dir . '/'; $dir = dir($dir); while (false !== ($file = $dir->read())){ if ($file === '.' || $file === '..') continue; $file = $prefix . $file; if (is_dir($file)) findFiles($file, $pattern); if (preg_match($pattern, $file)){ echo $file . "\n"; } } } findFiles('./foo', '/\.bar$/');
Can you help me rewrite this code in PHP instead of D, keeping it the same logically?
void main() { import std.stdio, std.file; dirEntries("", "*.d", SpanMode.breadth).writeln; }
function findFiles($dir = '.', $pattern = '/./'){ $prefix = $dir . '/'; $dir = dir($dir); while (false !== ($file = $dir->read())){ if ($file === '.' || $file === '..') continue; $file = $prefix . $file; if (is_dir($file)) findFiles($file, $pattern); if (preg_match($pattern, $file)){ echo $file . "\n"; } } } findFiles('./foo', '/\.bar$/');
Can you help me rewrite this code in PHP instead of Delphi, keeping it the same logically?
program Walk_a_directory; uses System.IOUtils; var Files: TArray<string>; FileName, Directory: string; begin Directory := TDirectory.GetCurrentDirectory; Files := TDirectory.GetFiles(Directory, '*.*', TSearchOption.soAllDirectories); for FileName in Files do begin Writeln(FileName); end; Readln; end.
function findFiles($dir = '.', $pattern = '/./'){ $prefix = $dir . '/'; $dir = dir($dir); while (false !== ($file = $dir->read())){ if ($file === '.' || $file === '..') continue; $file = $prefix . $file; if (is_dir($file)) findFiles($file, $pattern); if (preg_match($pattern, $file)){ echo $file . "\n"; } } } findFiles('./foo', '/\.bar$/');
Please provide an equivalent version of this Elixir code in PHP.
defmodule Walk_directory do def recursive(dir \\ ".") do Enum.each(File.ls!(dir), fn file -> IO.puts fname = " if File.dir?(fname), do: recursive(fname) end) end end Walk_directory.recursive
function findFiles($dir = '.', $pattern = '/./'){ $prefix = $dir . '/'; $dir = dir($dir); while (false !== ($file = $dir->read())){ if ($file === '.' || $file === '..') continue; $file = $prefix . $file; if (is_dir($file)) findFiles($file, $pattern); if (preg_match($pattern, $file)){ echo $file . "\n"; } } } findFiles('./foo', '/\.bar$/');
Can you help me rewrite this code in PHP instead of Erlang, keeping it the same logically?
walk_dir(Path, Pattern) -> filelib:fold_files( Path, Pattern, true, fun(File, Accumulator) -> [File|Accumulator] end, [] )
function findFiles($dir = '.', $pattern = '/./'){ $prefix = $dir . '/'; $dir = dir($dir); while (false !== ($file = $dir->read())){ if ($file === '.' || $file === '..') continue; $file = $prefix . $file; if (is_dir($file)) findFiles($file, $pattern); if (preg_match($pattern, $file)){ echo $file . "\n"; } } } findFiles('./foo', '/\.bar$/');
Rewrite the snippet below in PHP so it works the same as the original F# code.
open System.IO let rec getAllFiles dir pattern = seq { yield! Directory.EnumerateFiles(dir, pattern) for d in Directory.EnumerateDirectories(dir) do yield! getAllFiles d pattern } getAllFiles "c:\\temp" "*.xml" |> Seq.iter (printfn "%s")
function findFiles($dir = '.', $pattern = '/./'){ $prefix = $dir . '/'; $dir = dir($dir); while (false !== ($file = $dir->read())){ if ($file === '.' || $file === '..') continue; $file = $prefix . $file; if (is_dir($file)) findFiles($file, $pattern); if (preg_match($pattern, $file)){ echo $file . "\n"; } } } findFiles('./foo', '/\.bar$/');
Change the programming language of this snippet from Factor to PHP without modifying what it does.
USE: io.directories.search "." t [ dup ".factor" tail? [ print ] [ drop ] if ] each-file
function findFiles($dir = '.', $pattern = '/./'){ $prefix = $dir . '/'; $dir = dir($dir); while (false !== ($file = $dir->read())){ if ($file === '.' || $file === '..') continue; $file = $prefix . $file; if (is_dir($file)) findFiles($file, $pattern); if (preg_match($pattern, $file)){ echo $file . "\n"; } } } findFiles('./foo', '/\.bar$/');
Port the provided Forth code into PHP while preserving the original functionality.
"*.c" f:rglob
function findFiles($dir = '.', $pattern = '/./'){ $prefix = $dir . '/'; $dir = dir($dir); while (false !== ($file = $dir->read())){ if ($file === '.' || $file === '..') continue; $file = $prefix . $file; if (is_dir($file)) findFiles($file, $pattern); if (preg_match($pattern, $file)){ echo $file . "\n"; } } } findFiles('./foo', '/\.bar$/');
Convert this Groovy snippet to PHP and keep its semantics consistent.
new File('.').eachFileRecurse { if (it.name =~ /.*\.txt/) println it; }
function findFiles($dir = '.', $pattern = '/./'){ $prefix = $dir . '/'; $dir = dir($dir); while (false !== ($file = $dir->read())){ if ($file === '.' || $file === '..') continue; $file = $prefix . $file; if (is_dir($file)) findFiles($file, $pattern); if (preg_match($pattern, $file)){ echo $file . "\n"; } } } findFiles('./foo', '/\.bar$/');
Translate the given Haskell code snippet into PHP without altering its behavior.
import System.Environment import System.Directory import System.FilePath.Find search pat = find always (fileName ~~? pat) main = do [pat] <- getArgs dir <- getCurrentDirectory files <- search pat dir mapM_ putStrLn files
function findFiles($dir = '.', $pattern = '/./'){ $prefix = $dir . '/'; $dir = dir($dir); while (false !== ($file = $dir->read())){ if ($file === '.' || $file === '..') continue; $file = $prefix . $file; if (is_dir($file)) findFiles($file, $pattern); if (preg_match($pattern, $file)){ echo $file . "\n"; } } } findFiles('./foo', '/\.bar$/');
Rewrite this program in PHP while keeping its functionality equivalent to the J version.
require 'dir' >{."1 dirtree '*.html'
function findFiles($dir = '.', $pattern = '/./'){ $prefix = $dir . '/'; $dir = dir($dir); while (false !== ($file = $dir->read())){ if ($file === '.' || $file === '..') continue; $file = $prefix . $file; if (is_dir($file)) findFiles($file, $pattern); if (preg_match($pattern, $file)){ echo $file . "\n"; } } } findFiles('./foo', '/\.bar$/');
Rewrite this program in PHP while keeping its functionality equivalent to the Julia version.
rootpath = "/home/user/music" pattern = r".mp3$" for (root, dirs, files) in walkdir(rootpath) for file in files if occursin(pattern, file) println(file) end end end
function findFiles($dir = '.', $pattern = '/./'){ $prefix = $dir . '/'; $dir = dir($dir); while (false !== ($file = $dir->read())){ if ($file === '.' || $file === '..') continue; $file = $prefix . $file; if (is_dir($file)) findFiles($file, $pattern); if (preg_match($pattern, $file)){ echo $file . "\n"; } } } findFiles('./foo', '/\.bar$/');
Transform the following Lua implementation into PHP, maintaining the same output and logic.
local lfs = require("lfs") function find(self, fn) return coroutine.wrap(function() for f in lfs.dir(self) do if f ~= "." and f ~= ".." then local _f = self .. "/" .. f if not fn or fn(_f) then coroutine.yield(_f) end if lfs.attributes(_f, "mode") == "directory" then for n in find(_f, fn) do coroutine.yield(n) end end end end end) end for f in find("directory") do print(f) end for f in find("directory", function(self) return self:match("%.lua$") end) do print(f) end for f in find("directory", function(self) return "directory" == lfs.attributes(self, "mode") end) do print(f) end
function findFiles($dir = '.', $pattern = '/./'){ $prefix = $dir . '/'; $dir = dir($dir); while (false !== ($file = $dir->read())){ if ($file === '.' || $file === '..') continue; $file = $prefix . $file; if (is_dir($file)) findFiles($file, $pattern); if (preg_match($pattern, $file)){ echo $file . "\n"; } } } findFiles('./foo', '/\.bar$/');
Convert the following code from Mathematica to PHP, ensuring the logic remains intact.
FileNames["*"] FileNames["*.png", $RootDirectory] FileNames["*", {"*"}, Infinity]
function findFiles($dir = '.', $pattern = '/./'){ $prefix = $dir . '/'; $dir = dir($dir); while (false !== ($file = $dir->read())){ if ($file === '.' || $file === '..') continue; $file = $prefix . $file; if (is_dir($file)) findFiles($file, $pattern); if (preg_match($pattern, $file)){ echo $file . "\n"; } } } findFiles('./foo', '/\.bar$/');
Produce a language-to-language conversion: from MATLAB to PHP, same semantics.
function walk_a_directory_recursively(d, pattern) f = dir(fullfile(d,pattern)); for k = 1:length(f) fprintf(' end; f = dir(d); n = find([f.isdir]); for k=n(:)' if any(f(k).name~='.') walk_a_directory_recursively(fullfile(d,f(k).name), pattern); end; end; end;
function findFiles($dir = '.', $pattern = '/./'){ $prefix = $dir . '/'; $dir = dir($dir); while (false !== ($file = $dir->read())){ if ($file === '.' || $file === '..') continue; $file = $prefix . $file; if (is_dir($file)) findFiles($file, $pattern); if (preg_match($pattern, $file)){ echo $file . "\n"; } } } findFiles('./foo', '/\.bar$/');
Convert this Nim block to PHP, preserving its control flow and logic.
import os, re for file in walkDirRec "/": if file.match re".*\.mp3": echo file
function findFiles($dir = '.', $pattern = '/./'){ $prefix = $dir . '/'; $dir = dir($dir); while (false !== ($file = $dir->read())){ if ($file === '.' || $file === '..') continue; $file = $prefix . $file; if (is_dir($file)) findFiles($file, $pattern); if (preg_match($pattern, $file)){ echo $file . "\n"; } } } findFiles('./foo', '/\.bar$/');
Port the following code from OCaml to PHP with equivalent syntax and logic.
#!/usr/bin/env ocaml #load "unix.cma" #load "str.cma" open Unix let walk_directory_tree dir pattern = let re = Str.regexp pattern in let select str = Str.string_match re str 0 in let rec walk acc = function | [] -> (acc) | dir::tail -> let contents = Array.to_list (Sys.readdir dir) in let contents = List.rev_map (Filename.concat dir) contents in let dirs, files = List.fold_left (fun (dirs,files) f -> match (stat f).st_kind with | S_REG -> (dirs, f::files) | S_DIR -> (f::dirs, files) | _ -> (dirs, files) ) ([],[]) contents in let matched = List.filter (select) files in walk (matched @ acc) (dirs @ tail) in walk [] [dir] ;; let () = let results = walk_directory_tree "/usr/local/lib/ocaml" ".*\\.cma" in List.iter print_endline results; ;;
function findFiles($dir = '.', $pattern = '/./'){ $prefix = $dir . '/'; $dir = dir($dir); while (false !== ($file = $dir->read())){ if ($file === '.' || $file === '..') continue; $file = $prefix . $file; if (is_dir($file)) findFiles($file, $pattern); if (preg_match($pattern, $file)){ echo $file . "\n"; } } } findFiles('./foo', '/\.bar$/');
Convert the following code from Perl to PHP, ensuring the logic remains intact.
use File::Find qw(find); my $dir = '.'; my $pattern = 'foo'; my $callback = sub { print $File::Find::name, "\n" if /$pattern/ }; find $callback, $dir;
function findFiles($dir = '.', $pattern = '/./'){ $prefix = $dir . '/'; $dir = dir($dir); while (false !== ($file = $dir->read())){ if ($file === '.' || $file === '..') continue; $file = $prefix . $file; if (is_dir($file)) findFiles($file, $pattern); if (preg_match($pattern, $file)){ echo $file . "\n"; } } } findFiles('./foo', '/\.bar$/');
Translate this program into PHP but keep the logic exactly as in PowerShell.
Get-ChildItem -Recurse -Include *.mp3
function findFiles($dir = '.', $pattern = '/./'){ $prefix = $dir . '/'; $dir = dir($dir); while (false !== ($file = $dir->read())){ if ($file === '.' || $file === '..') continue; $file = $prefix . $file; if (is_dir($file)) findFiles($file, $pattern); if (preg_match($pattern, $file)){ echo $file . "\n"; } } } findFiles('./foo', '/\.bar$/');
Produce a language-to-language conversion: from R to PHP, same semantics.
dir("/bar/foo", "mp3",recursive=T)
function findFiles($dir = '.', $pattern = '/./'){ $prefix = $dir . '/'; $dir = dir($dir); while (false !== ($file = $dir->read())){ if ($file === '.' || $file === '..') continue; $file = $prefix . $file; if (is_dir($file)) findFiles($file, $pattern); if (preg_match($pattern, $file)){ echo $file . "\n"; } } } findFiles('./foo', '/\.bar$/');
Convert this Racket snippet to PHP and keep its semantics consistent.
-> (for ([f (in-directory "/tmp")] #:when (regexp-match? "\\.rkt$" f)) (displayln f)) ... *.rkt files including in nested directories ...
function findFiles($dir = '.', $pattern = '/./'){ $prefix = $dir . '/'; $dir = dir($dir); while (false !== ($file = $dir->read())){ if ($file === '.' || $file === '..') continue; $file = $prefix . $file; if (is_dir($file)) findFiles($file, $pattern); if (preg_match($pattern, $file)){ echo $file . "\n"; } } } findFiles('./foo', '/\.bar$/');
Keep all operations the same but rewrite the snippet in PHP.
* List all file names on my disk D: that contain the string TTTT *--------------------------------------------------------------------*/ call SysFileTree "d:\*.*", "file", "FS" -- F get all Files -- S search subdirectories Say file.0 'files on disk' do i=1 to file.0 If pos('TTTT',translate(file.i))>0 Then say file.i end
function findFiles($dir = '.', $pattern = '/./'){ $prefix = $dir . '/'; $dir = dir($dir); while (false !== ($file = $dir->read())){ if ($file === '.' || $file === '..') continue; $file = $prefix . $file; if (is_dir($file)) findFiles($file, $pattern); if (preg_match($pattern, $file)){ echo $file . "\n"; } } } findFiles('./foo', '/\.bar$/');
Generate an equivalent PHP version of this Ruby code.
require 'find' Find.find('/your/path') do |f| puts f if f.match(/\.mp3\Z/) end
function findFiles($dir = '.', $pattern = '/./'){ $prefix = $dir . '/'; $dir = dir($dir); while (false !== ($file = $dir->read())){ if ($file === '.' || $file === '..') continue; $file = $prefix . $file; if (is_dir($file)) findFiles($file, $pattern); if (preg_match($pattern, $file)){ echo $file . "\n"; } } } findFiles('./foo', '/\.bar$/');
Write the same algorithm in PHP as shown in this Scala implementation.
import java.io.File fun walkDirectoryRecursively(dirPath: String, pattern: Regex): Sequence<String> { val d = File(dirPath) require (d.exists() && d.isDirectory()) return d.walk().map { it.name }.filter { it.matches(pattern) }.sorted().distinct() } fun main(args: Array<String>) { val r = Regex("""^v(a|f).*\.h$""") val files = walkDirectoryRecursively("/usr/include", r) for (file in files) println(file) }
function findFiles($dir = '.', $pattern = '/./'){ $prefix = $dir . '/'; $dir = dir($dir); while (false !== ($file = $dir->read())){ if ($file === '.' || $file === '..') continue; $file = $prefix . $file; if (is_dir($file)) findFiles($file, $pattern); if (preg_match($pattern, $file)){ echo $file . "\n"; } } } findFiles('./foo', '/\.bar$/');
Ensure the translated PHP code behaves exactly like the original Swift snippet.
import Foundation let fileSystem = FileManager.default let rootPath = "/" if let fsTree = fileSystem.enumerator(atPath: rootPath) { while let fsNodeName = fsTree.nextObject() as? NSString { let fullPath = "\(rootPath)/\(fsNodeName)" var isDir: ObjCBool = false fileSystem.fileExists(atPath: fullPath, isDirectory: &isDir) if !isDir.boolValue && fsNodeName.pathExtension == "txt" { print(fsNodeName) } } }
function findFiles($dir = '.', $pattern = '/./'){ $prefix = $dir . '/'; $dir = dir($dir); while (false !== ($file = $dir->read())){ if ($file === '.' || $file === '..') continue; $file = $prefix . $file; if (is_dir($file)) findFiles($file, $pattern); if (preg_match($pattern, $file)){ echo $file . "\n"; } } } findFiles('./foo', '/\.bar$/');
Write the same code in PHP as shown below in Tcl.
package require fileutil proc walkin {path cmd} { set normalized [::fileutil::fullnormalize $path] set myname [lindex [info level 0] 0] set children [glob -nocomplain -directory $path -types hidden *] lappend children {*}[glob -nocomplain -directory $path *] foreach child $children[set children {}] { if {[file tail $child] in {. ..}} { continue } if {[file isdirectory $child]} { if {[file type $child] eq "link"} { set normalizedchild [fileutil::fullnormalize $child] if {[string first $normalized/ $normalizedchild] == 0} { } else { $myname $child $cmd } } } {*}$cmd $child } } walkin /home/usr {apply {fname { set tail [file tail $fname] if {[string match *.mp3 $tail]} { puts $fname } }}}
function findFiles($dir = '.', $pattern = '/./'){ $prefix = $dir . '/'; $dir = dir($dir); while (false !== ($file = $dir->read())){ if ($file === '.' || $file === '..') continue; $file = $prefix . $file; if (is_dir($file)) findFiles($file, $pattern); if (preg_match($pattern, $file)){ echo $file . "\n"; } } } findFiles('./foo', '/\.bar$/');
Please provide an equivalent version of this C++ code in Rust.
#include "boost/filesystem.hpp" #include "boost/regex.hpp" #include <iostream> using namespace boost::filesystem; int main() { path current_dir("."); boost::regex pattern("a.*"); for (recursive_directory_iterator iter(current_dir), end; iter != end; ++iter) { std::string name = iter->path().filename().string(); if (regex_match(name, pattern)) std::cout << iter->path() << "\n"; } }
#![feature(fs_walk)] use std::fs; use std::path::Path; fn main() { for f in fs::walk_dir(&Path::new("/home/pavel/Music")).unwrap() { let p = f.unwrap().path(); if p.extension().unwrap_or("".as_ref()) == "mp3" { println!("{:?}", p); } } }
Produce a functionally identical Rust code for the snippet given in C#.
using System; using System.Collections.Generic; using System.IO; using System.Linq; namespace RosettaRecursiveDirectory { class Program { static IEnumerable<FileInfo> TraverseDirectory(string rootPath, Func<FileInfo, bool> Pattern) { var directoryStack = new Stack<DirectoryInfo>(); directoryStack.Push(new DirectoryInfo(rootPath)); while (directoryStack.Count > 0) { var dir = directoryStack.Pop(); try { foreach (var i in dir.GetDirectories()) directoryStack.Push(i); } catch (UnauthorizedAccessException) { continue; } foreach (var f in dir.GetFiles().Where(Pattern)) yield return f; } } static void Main(string[] args) { foreach (var file in TraverseDirectory(@"C:\Windows", f => f.Extension == ".wmv")) Console.WriteLine(file.FullName); Console.WriteLine("Done."); } } }
#![feature(fs_walk)] use std::fs; use std::path::Path; fn main() { for f in fs::walk_dir(&Path::new("/home/pavel/Music")).unwrap() { let p = f.unwrap().path(); if p.extension().unwrap_or("".as_ref()) == "mp3" { println!("{:?}", p); } } }
Convert this Java snippet to Rust and keep its semantics consistent.
import java.io.File; public class MainEntry { public static void main(String[] args) { walkin(new File("/home/user")); } public static void walkin(File dir) { String pattern = ".mp3"; File listFile[] = dir.listFiles(); if (listFile != null) { for (int i=0; i<listFile.length; i++) { if (listFile[i].isDirectory()) { walkin(listFile[i]); } else { if (listFile[i].getName().endsWith(pattern)) { System.out.println(listFile[i].getPath()); } } } } } }
#![feature(fs_walk)] use std::fs; use std::path::Path; fn main() { for f in fs::walk_dir(&Path::new("/home/pavel/Music")).unwrap() { let p = f.unwrap().path(); if p.extension().unwrap_or("".as_ref()) == "mp3" { println!("{:?}", p); } } }
Rewrite this program in Rust while keeping its functionality equivalent to the Go version.
package main import ( "fmt" "os" "path/filepath" ) func VisitFile(fp string, fi os.FileInfo, err error) error { if err != nil { fmt.Println(err) return nil } if fi.IsDir() { return nil } matched, err := filepath.Match("*.mp3", fi.Name()) if err != nil { fmt.Println(err) return err } if matched { fmt.Println(fp) } return nil } func main() { filepath.Walk("/", VisitFile) }
#![feature(fs_walk)] use std::fs; use std::path::Path; fn main() { for f in fs::walk_dir(&Path::new("/home/pavel/Music")).unwrap() { let p = f.unwrap().path(); if p.extension().unwrap_or("".as_ref()) == "mp3" { println!("{:?}", p); } } }
Please provide an equivalent version of this Rust code in Python.
#![feature(fs_walk)] use std::fs; use std::path::Path; fn main() { for f in fs::walk_dir(&Path::new("/home/pavel/Music")).unwrap() { let p = f.unwrap().path(); if p.extension().unwrap_or("".as_ref()) == "mp3" { println!("{:?}", p); } } }
from pathlib import Path for path in Path('.').rglob('*.*'): print(path)
Convert this C block to Rust, preserving its control flow and logic.
#include <sys/types.h> #include <sys/stat.h> #include <unistd.h> #include <dirent.h> #include <regex.h> #include <stdio.h> #include <string.h> #include <errno.h> #include <err.h> enum { WALK_OK = 0, WALK_BADPATTERN, WALK_NAMETOOLONG, WALK_BADIO, }; #define WS_NONE 0 #define WS_RECURSIVE (1 << 0) #define WS_DEFAULT WS_RECURSIVE #define WS_FOLLOWLINK (1 << 1) #define WS_DOTFILES (1 << 2) #define WS_MATCHDIRS (1 << 3) int walk_recur(char *dname, regex_t *reg, int spec) { struct dirent *dent; DIR *dir; struct stat st; char fn[FILENAME_MAX]; int res = WALK_OK; int len = strlen(dname); if (len >= FILENAME_MAX - 1) return WALK_NAMETOOLONG; strcpy(fn, dname); fn[len++] = '/'; if (!(dir = opendir(dname))) { warn("can't open %s", dname); return WALK_BADIO; } errno = 0; while ((dent = readdir(dir))) { if (!(spec & WS_DOTFILES) && dent->d_name[0] == '.') continue; if (!strcmp(dent->d_name, ".") || !strcmp(dent->d_name, "..")) continue; strncpy(fn + len, dent->d_name, FILENAME_MAX - len); if (lstat(fn, &st) == -1) { warn("Can't stat %s", fn); res = WALK_BADIO; continue; } if (S_ISLNK(st.st_mode) && !(spec & WS_FOLLOWLINK)) continue; if (S_ISDIR(st.st_mode)) { if ((spec & WS_RECURSIVE)) walk_recur(fn, reg, spec); if (!(spec & WS_MATCHDIRS)) continue; } if (!regexec(reg, fn, 0, 0, 0)) puts(fn); } if (dir) closedir(dir); return res ? res : errno ? WALK_BADIO : WALK_OK; } int walk_dir(char *dname, char *pattern, int spec) { regex_t r; int res; if (regcomp(&r, pattern, REG_EXTENDED | REG_NOSUB)) return WALK_BADPATTERN; res = walk_recur(dname, &r, spec); regfree(&r); return res; } int main() { int r = walk_dir(".", ".\\.c$", WS_DEFAULT|WS_MATCHDIRS); switch(r) { case WALK_OK: break; case WALK_BADIO: err(1, "IO error"); case WALK_BADPATTERN: err(1, "Bad pattern"); case WALK_NAMETOOLONG: err(1, "Filename too long"); default: err(1, "Unknown error?"); } return 0; }
#![feature(fs_walk)] use std::fs; use std::path::Path; fn main() { for f in fs::walk_dir(&Path::new("/home/pavel/Music")).unwrap() { let p = f.unwrap().path(); if p.extension().unwrap_or("".as_ref()) == "mp3" { println!("{:?}", p); } } }
Preserve the algorithm and functionality while converting the code from Rust to VB.
#![feature(fs_walk)] use std::fs; use std::path::Path; fn main() { for f in fs::walk_dir(&Path::new("/home/pavel/Music")).unwrap() { let p = f.unwrap().path(); if p.extension().unwrap_or("".as_ref()) == "mp3" { println!("{:?}", p); } } }
Sub printFiles(parentDir As FolderItem, pattern As String) For i As Integer = 1 To parentDir.Count If parentDir.Item(i).Directory Then printFiles(parentDir.Item(i), pattern) Else Dim rg as New RegEx Dim myMatch as RegExMatch rg.SearchPattern = pattern myMatch = rg.search(parentDir.Item(i).Name) If myMatch <> Nil Then Print(parentDir.Item(i).AbsolutePath) End If Next End Sub