【发布时间】:2012-09-23 16:54:38
【问题描述】:
Goodday,我有脚本,它循环目录中的所有文件,但我需要隐藏控制台,同时以这种方式循环它们。 这是脚本的一部分:
#include <iostream>
#include <fstream>
#include <Windows.h>
using namespace std;
int GetFilesInDirectory(const char * dir,string dest[],unsigned int max){
string loc=dir;
int ctr=0;
if(loc.length()>2)
if(loc.substr(loc.length()-2,1)=="\\")
loc=loc.substr(0,loc.length()-1);
string opcommand;
string delcommand;
if(loc.length()>2){
opcommand="cd "+(loc)+" && dir /s /b /a > tmpfile.cpptmp";
delcommand="cd "+(loc)+" && del tmpfile.cpptmp";
} else {
opcommand="dir /s /b /a > tmpfile.cpptmp";
delcommand="del tmpfile.cpptmp";
}
system(opcommand.c_str());
ifstream f;
string line;
string fileloc;
if(loc.length()>2)
fileloc=(loc)+"\\tmpfile.cpptmp";
else fileloc="tmpfile.cpptmp";
f.open(fileloc,ios::binary);
while(f.good()){
getline(f,line);
if(line.length()>1&&ctr<max){
dest[ctr]=line;
ctr++;
}
}
f.close();
system(delcommand.c_str());
return ctr;
}
int main() {
FreeConsole();
const unsigned int filescountmax=16184;
string files[filescountmax];
int count=GetFilesInDirectory("\\",files,filescountmax);
string ext;
for(int i=0;i<count;i++){
//some script
}
}
当进程启动时,它会自行隐藏它,但之后它会显示 cmd.exe,它会自行关闭它。 顺便说一句,我知道还有其他方法可以循环目录中的文件,但这是循环子目录和子目录的子目录等中的文件的最简单方法。 你能帮帮我吗?
【问题讨论】:
-
我认为
CreateProcess可用于在不显示命令提示符的情况下拨打system。 -
@WaleedKhan,我很确定你可以将第四个参数指定给
WinMain,所以只要进程使用它来确定状态,那就对了。 -
如果要列出和删除目录中的文件,为什么不使用为此提供的 Windows API 函数呢?例如,有一个tutorial on listing directory contents。执行
cmd.exe来做这些事情有点傻——就像你用 C++ 编写了一个批处理文件。 -
或者您可以使用 boost 并让解决方案跨平台。你甚至可以试试 TR2 的
<filesystem>标头。 -
我不知道如何使用 CreateProcess :(