通过这个片段,我尝试从目录中删除某个文件。这是代码。
/* char* cpathToDeleteGND;
char* cpathToDeleteFST;
char* cpathToDeleteSND;
*/
cout << "Enter the name to be removed : ";
cin.ignore();
getline( cin , fullName );
string pathToDeleteGND = "d:/HostelManager/studentDetails/groundFloor/" + fullName + ".txt";
string pathToDeleteFST = "d:/HostelManager/studentDetails/firstFloor/" + fullName + ".txt";
string pathToDeleteSND = "d:/HostelManager/studentDetails/secondFloor/" + fullName + ".txt";
ifstream checkToDeleteGND( pathToDeleteGND );
ifstream checkToDeleteFST( pathToDeleteFST );
ifstream checkToDeleteSND( pathToDeleteSND );
cpathToDeleteGND = new char[ pathToDeleteGND.size() + 1 ];
cpathToDeleteFST = new char[ pathToDeleteFST.size() + 1 ];
cpathToDeleteSND = new char[ pathToDeleteSND.size() + 1 ];
strcpy( cpathToDeleteGND , pathToDeleteGND.c_str() );
strcpy( cpathToDeleteFST , pathToDeleteFST.c_str() );
strcpy( cpathToDeleteSND , pathToDeleteSND.c_str() );
if( checkToDeleteGND ) {
if( remove( cpathToDeleteGND) == 0 ) {
cout << "\nStudent details cleared successfully !";
}
} else if( checkToDeleteFST) {
if( remove( cpathToDeleteFST) == 0 ) {
cout << "\nStudent details cleared successfully ! ";
}
} else if( checkToDeleteSND ) {
if( remove( cpathToDeleteSND) == 0 ) {
cout << "\nStudent details cleared successfully !";
}
} else {
cout << "\nIt seems that either the student has already been removed or does not exist.";
}
我给出了应该从目录中删除的名称。尽管if else阻止工作,但remove功能不起作用。我不明白原因..
例如,输出如下:
Enter the name to be removed : diana
Press any key to continue . . .
存在文件
diana.txt
,这就是为什么它不执行最后一个else
块的原因。但是remove function
不起作用。 为什么? 最佳答案
您不知道,因为仅当remove
成功时才打印一条消息。尝试:
if (remove(pathToDeleteFST.c_str()) == 0) {
// success, print something
} else {
// failure, much more interesting
cout << "Can't remove " << pathToDeleteFST << ": "
<< strerror(errno) << endl;
}
errno
在errno.h
中,strerror
在string.h
中。(除了打开文件检查文件是否存在之外,您还可以提前充电并尝试用
remove
编码。如@ n.m。所述,在Windows上甚至可能是必需的。)关于c++ - 删除无法正常工作? (属于std namespace ),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/6676953/