我的代码:
cleaner.hpp
[C++] 纯文本查看 复制代码 /*
* Copyright (C) 2023 JuRuoqwq
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <[url]https://www.gnu.org/licenses/>.[/url]
*/
#ifndef CLEANER_HPP
#define CLEANER_HPP
// C++标准库
#include <string>
#include <cstdlib>
#include <vector>
#include <fstream>
#include <iostream>
/*
* 清理的状态
*/
struct CleanStates {
const int CLEAN_OK = 0;
const int FILE_NOT_FOUND = -1;
const int CAN_NOT_DEL_FILE = -2;
}states;
class Cleaner {
public:
// 构造函数
Cleaner();
Cleaner(std::vector<std::string> fileNames);
// 成员函数
int DeleteObjectFile();
private:
std::vector<std::string> fileNames;
};
#endif
cleaner.cpp:
[C++] 纯文本查看 复制代码 /*
* Copyright (C) 2023 JuRuoqwq
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <[url]https://www.gnu.org/licenses/>.[/url]
*/
#include "cleaner.hpp"
/*
* Cleaner的默认构造函数
*/
Cleaner::Cleaner() {
(*this).fileNames = {};
}
/*
* 包含了要删除的文件的文件名的构造函数
*/
Cleaner::Cleaner(std::vector<std::string> fileNames) {
(*this).fileNames = fileNames;
}
/*
* 删除对象文件(.o .obj)
*/
int Cleaner::DeleteObjectFile() {
std::ifstream inFileStream; //读文件的文件流
std::string delFileCommand;
int result;
for (auto fileName : fileNames) {
inFileStream.open(fileName);
if (inFileStream.is_open()) {
// 文件存在,删除
#if _WIN32
delFileCommand = "del /q" + (std::string)" " + fileName;
#else
delFileCommand = "rm -rf" + (std::string)" " + fileName;
#endif
int commandRunState = system(delFileCommand.c_str());
if (result == -1) {
result = states.CAN_NOT_DEL_FILE;
}
}else {
result = states.FILE_NOT_FOUND;
}
}
result = states.CLEAN_OK;
return result;
}
// test
int main() {
std::vector<std::string> fileNames = {"a.o","b.o","c.o"};
Cleaner test(fileNames);
test.DeleteObjectFile();
}
问题应该是出现在cleaner.cpp的line 49,执行CMD命令的地方
在fileNames(line 67)中,位于向量第一个字符串(在这里是"a.o")在删除的时候会提示被占用,但是使用cmd可以删除,这有在这个程序里不行
而且我也尝试了一下,把a.o和b.o调换,结局是b.o无法被删除
这是为什么?
|