I'm trying to execute MS-DOS DEL
commands inside a Win32 C program, and I already know tha开发者_运维技巧t system
and popen
can be used for this. However, the problem is that both require string literals (type const char
) for the commands, and I need something like the DOS equivalent of this Perl code (more or less, don't know if it actually works):
my $user = $ENV{'USERNAME'};
my $directory = $ENV{'HOME'};
my $files = system("dir " . $directory);
my $pattern = "s/(\d{7,8})|(\"" . $user . "\")/";
$files ~= $pattern;
system("rm " . $files);
which obviously has to use string literals for the rm
command. Is there some other subprocess function in C that allows for char arrays as arguments for process names?
Its a pain, but you will probably end up having to un-escape all the escape characters. "\blah"
-> "\\blah"
, etc. See a list of them here.
Based on your code, I would do something like (roughly):
pattern = "s/(\\d{7,8})|(\\\"%s\\\")/";
char buff[100];
sprintf(buff, getenv("HOME"));
system(buff);
The idea being specify the pattern with all the troubling characters escaped, i.e \\
and \"
, then use sprintf
to get the final format string. The string from getenv will not have escape character problems, so you can use it directly.
精彩评论