I'd like to use all files that match some trivial glob as a main argument.
For example, if I need to go through all txt files in folder "X", I'd like to start my program in Command Prompt as something like my_prog C:\X\*.txt
How can I manage this?
I'd like to use all files that match some trivial glob as a main argument.
For example, if I need to go through all txt files in folder "X", I'd like to start my program in Command Prompt as something like my_prog C:\X\*.txt
How can I manage this?
This asterisk *
that you used in your example is not a part of your program.
It would be the duty of OS to manage that! And it would be a WildCard
In fact you wanted to use 2
arguments in your code. One for path and another for a regex.
You should take these 2 arguments into your main program and then paring them.
#include <iostream>
int main(int argc, char** argv) {
std::cout << argv[ 1 ] << ": " << argv[ 2 ] << std::endl;
}
Input
program folder *.txt
Output
folder: *.txt
Now it is your opinion to how to implement the algorithm that can go through all your files in your directory and than find the matched one
Regarding to this: Globbing in C++/C, on Windows
I've linked setargv.obj
to my project and it perfectly works:
for (int i = 1; i < argc; i++) {
std::cout << argv[i] << '\n';
}
In C++17, there is a new standard <filesystem>
library that helps manipulate paths and filenames in a portable way for Unix-style and Windows-style operating systems.
Unix shells typically do globbing on behalf of the program, before spinning up the process, so programs simply receive the list of matching files in the argument vector. The trade-off here is that if you want to use any of those special characters on your command line (e.g., to pass an actual regular expression), the user has to know to use the proper escaping rules for the particular shell.
Windows (and other operating systems, like VMS) provide APIs the program can call to turn a wild-carded file specification into actual file names. The traditional way to do this in Windows is with FindFirstFile and FindNextFile. The trade-off here is that people often mess up the code for iterating through files using this API. There are a surprising number of ways to get it wrong.
The C++17 <filesystem>
library provides directory iterators (regular and recursive) that should abstract over many of the details of correctly using the OS's APIs.
for %%a in (c:\x\*.txt) do my_prog %%a
This is for direct command line. If you use .BAT file, use %a
instead of %%a
. for
loop will find all files and call my_prog
for each of them.