在C或C ++中控制Shell命令行通配符扩展 [英] Controlling shell command line wildcard expansion in C or C++

查看:37
本文介绍了在C或C ++中控制Shell命令行通配符扩展的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用C ++编写程序foo.通常在命令行上这样调用它:

I'm writing a program, foo, in C++. It's typically invoked on the command line like this:

foo *.txt

我的 main()以常规方式接收参数.在许多系统上, argv [1] 实际上是 *.txt ,我必须调用系统例程来进行通配符扩展.但是,在Unix系统上,shell会在调用我的程序之前先扩展通配符,并且所有匹配的文件名都将在 argv 中.

My main() receives the arguments in the normal way. On many systems, argv[1] is literally *.txt, and I have to call system routines to do the wildcard expansion. On Unix systems, however, the shell expands the wildcard before invoking my program, and all of the matching filenames will be in argv.

假设我想向foo添加一个开关,使它递归到子目录中.

Suppose I wanted to add a switch to foo that causes it to recurse into subdirectories.

foo -a *.txt

将处理当前目录及其所有子目录中的所有文本文件.

would process all text files in the current directory and all of its subdirectories.

我不知道如何完成此操作,因为当我的程序有机会看到 -a 时,shell已经完成了扩展,并且用户的 *.txt 输入丢失.但是,有一些通用的Unix程序可以这种方式工作.他们是如何做到的?

I don't see how this is done, since, by the time my program gets a chance to see the -a, then shell has already done the expansion and the user's *.txt input is lost. Yet there are common Unix programs that work this way. How do they do it?

在Unix领域中,如何控制通配符扩展?

In Unix land, how can I control the wildcard expansion?

(通过子目录递归只是一个示例.理想情况下,我试图了解控制通配符扩展的一般解决方案.)

(Recursing through subdirectories is just one example. Ideally, I'm trying to understand the general solution to controlling the wildcard expansion.)

推荐答案

您的程序对Shell的命令行扩展没有影响.在完成所有扩展后确定将要调用哪个程序,因此以编程方式更改有关扩展的任何内容已经为时已晚.

You program has no influence over the shell's command line expansion. Which program will be called is determined after all the expansion is done, so it's already too late to change anything about the expansion programmatically.

另一方面,调用程序的用户可以创建他喜欢的任何命令行.使用Shell,您通常可以通过将参数放在单引号中来轻松阻止通配符扩展:

The user calling your program, on the other hand, has the possibility to create whatever command line he likes. Shells allow you to easily prevent wildcard expansion, usually by putting the argument in single quotes:

program -a '*.txt'

如果这样调用程序,它将收到两个参数 -a *.txt .

If your program is called like that it will receive two parameters -a and *.txt.

在Unix上,如果不需要,应该将其留给用户以手动阻止通配符扩展.

On Unix, you should just leave it to the user to manually prevent wildcard expansion if it is not desired.

这篇关于在C或C ++中控制Shell命令行通配符扩展的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆