Reputation: 1
I'm trying to write a code that renames files in a directory (C:\BA\scrapers). In cmd you are prompted for input what file to rename ($filePointer) and then prompted for what the file name will be renamed to ($newFileName).
I am getting the following error: The system cannot find the file specified (code: 2)
function renameFile(){
$filePointer = rtrim(fgets(STDIN));
echo "\nEnter new file name: ";
$newFileName = rtrim(fgets(STDIN));
if(!rename($filePointer, $newFileName)){
echo ("$filePointer cannot be renamed due to an error");
}
else {
rename($filePointer, $newFileName);
}
}
I've tried specifying what directory to rename in, however I didn't manage to make it work. I'm a beginner, so please go easy on me.
Upvotes: 0
Views: 729
Reputation: 1
You must write something like this to make it work.
<?php
function renameFile(){
$myPath="C:\\BA\\scrapers\\";
echo "\nEnter old file name: ";
$filePointer =$myPath . rtrim(fgets(STDIN));
echo "\nEnter new file name: ";
$newFileName = $myPath .rtrim(fgets(STDIN));
if(!rename($filePointer, $newFileName)){
echo ("$filePointer cannot be renamed due to an error");
}
else {
echo "Successfully renamed";
}
}
?>
Upvotes: 0
Reputation:
You are renaming the file twice. After you renamed it in
if(!rename($filePointer, $newFileName)){
it obviously doesn't exist to rename it again in
else {
rename($filePointer, $newFileName);
}
Remove the else
block
Upvotes: 1