【发布时间】:2015-04-26 17:31:26
【问题描述】:
我重命名文件的代码部分不起作用。我尝试在另一个项目中单独编写它,它可以工作。请帮帮我。
#include <iostream>
#include <stdio.h>
#include <fstream>
using namespace std;
int main () {
char address[] = "";
char newname[] = "";
int action;
char confirm;
int result;
cout << "File Manipulator 1.0" << endl;
cout << "--------------------" << endl << endl;
cout << "Type the full address of a file you wish to manipulate." << endl << endl;
ADDRESS:cin >> address;
fstream file(address);
if (!file.good()) {
cout << "The selected file does not exist! Try again. ";
goto ADDRESS;
} else {
cout << endl << "-----------------------------------" << endl;
cout << "Type 1 to move the selected file." << endl;
cout << "Type 2 to rename the selected file." << endl;
cout << "Type 3 to delete the selected file." << endl;
cout << "-----------------------------------" << endl << endl;
ACTION:cin >> action;
if (action == 1) {
cout << 1;
} else if (action == 2) {
cout << "Enter the new name: ";
cin >> newname;
cout << "Are you sure you want to rename the selected file? Y/N ";
CONFIRM:cin >> confirm;
if (confirm == 'Y' || 'y') {
result = rename(address, newname);
if (result == 0) {
cout << "renamed";
} else {
perror("not renamed");
}
} else if (confirm == 'N' || 'n') {
cout << "No";
} else {
cout << "You typed an invalid command! Try again. ";
goto CONFIRM;
}
} else if (action == 3) {
cout << 3;
} else {
cout << "You typed an invalid command! Try again." << endl;
goto ACTION;
}
}
return 0;
}
顺便说一句,整个代码还没有完成,所以只检查重命名部分。谢谢。
【问题讨论】:
-
什么平台?它在什么方面不起作用?
-
@AlanStokes 它只是不会重命名文件。这意味着
if (result == 0)条件在哪里弹出错误“未重命名”。 -
char address[] = "";声明一个长度为 1 的数组。长度是根据初始化程序计算的。然后,您通过写入该数组的末尾而导致缓冲区溢出,之后,所有赌注都关闭了。要解决此问题,您可以使用std::string而不是 char 数组。