简体   繁体   English

C ++对文件夹中的所有文件执行相同的代码

[英]C++ execute same code on all files in a folder

I have been surfing the net for really long time and I didn't even get close to any solution to this. 我已经上网很长时间了,甚至还没有找到任何解决方案。 Sorry if it seems trivial to experts. 抱歉,对专家而言,这是微不足道的。

I have a C++ code that takes a binary file as an input argument, does some computation then outputs a .csv file. 我有一个C ++代码,它将二进制文件作为输入参数,进行一些计算然后输出一个.csv文件。 So, I have been using the command line to execute the code over one or more files, as following 因此,我一直在使用命令行在一个或多个文件上执行代码,如下所示

MyProgram filename1 filename2 

In my case, I have all my files from filename1 to filenameN in a specific folder. 就我而言,我的所有文件都从filename1filenameN都位于特定的文件夹中。 I want to know if there is any way to input the folder name, so the program would be executed over all the files included. 我想知道是否可以通过任何方式输入文件夹名称,因此该程序将在包含的所有文件上执行。

Maybe something like this 也许像这样

Myprogram /Users/Whatever

or in windows like 或像

Myprogram C:\User\Whatever

Thanks in advance 提前致谢

For linux you can use command line with wild characters arguments like: YourProgram path/to/*.csv and you'll get all files match to the pattern path/to/*.csv into the argv array. 对于linux,您可以使用带有通配符参数的命令行,例如: YourProgram path/to/*.csv然后将与模式path/to/*.csv匹配的所有文件放入argv数组。

If it is windows you can use some Win API like FindFirstFile , FindNextFile to resolve the wild characters and get all match files. 如果是Windows,则可以使用某些Win API(如FindFirstFileFindNextFile)解析通配符并获取所有匹配文件。 you can also check this example : 您也可以查看以下示例

On *nix based consoles then the "xargs" command is your friend. 在基于* nix的控制台上,“ xargs”命令是您的朋友。 eg 例如

find ./MyDirectory -name "*.notcsv" | xargs myprogram

Personally I wouldn't modify the code itself to iterate through files as the operating system supplies a mechanism. 就个人而言,由于操作系统提供了一种机制,因此我不会修改代码本身以遍历文件。 It makes your program more "single responsibility". 它使您的程序更具“单一责任”。 If you send the output to stdout/cout it allows your program to be chained with other text processing commands if necessary. 如果将输出发送到stdout / cout,则可以在必要时将程序与其他文本处理命令链接在一起。

Cheers 干杯

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM