我想知道如何打印argv的特定部分。例如
import os
import re
def file_count_search(root_dir,keyword):
path_to_match_count={}
for dirpath,dirnames,filenames in os.walk(root_dir,topdown=True):
matches = re.findall(keyword, str(filenames))
path_to_match_count[os.path.join(root_dir,dirpath)] = len(matches)
print path_to_match_count
file_count_search("c://test","file")
这是我的代码,我只是不知道该放在那个地方
./program hello world
The first 3 letters of the first argument is:
1 = h
2 = e
3 = o
The full argument was: hello
The first 3 letters of the second argument is:
1 = w
2 = o
3 = r
The full argument was: world
答案 0 :(得分:1)
第一个参数在argv[1]
中,第二个参数在argv[2]
中,依此类推。要从其中打印单个字符,请添加另一级下标。
在打印参数之前,还应检查是否已提供参数,并且它们有足够的字符可在循环中打印。
int main(int argc, char **argv) {
if (argc >= 2) {
printf("The first 3 letters of the first argument is:\n");
int i = 0;
while (i < 3 && argv[1][i]) {
printf("%d = %c\n", i, argv[1][i]);
i++;
}
printf("The full word was: %s\n\n", argv[1]);
}
if (argc >= 3) {
printf("The first 3 letters of the second argument is:\n");
int j = 0;
while (j < 3 && argv[2][j]) {
printf("%d = %c\n", j, argv[2][j]);
j++;
}
printf("The full word was: %s\n", argv[2]);
}
}
答案 1 :(得分:1)
argv中的第一个元素是程序的名称,其余元素指向参数。每个参数的前三个字符可以通过在参数argv [1]到argv [n]中进行迭代来找到,同时为每个参数打印所需的字符。
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char **argv)
{
printf("Program: %s\n", argv[0]);
if (argc > 2)
{
int i = 1;
for ( ; i < argc ; i++)
{
if (!argv[i][2])
{
fprintf(stderr,"Length of argument \"%s\" is less than 3\n", argv[i]);
return(EXIT_FAILURE);
}
else
printf("The first 3 letters of argument %d is:\n", i);
int j = 0;
while(j < 3)
{
printf("Index %d in agument \"%s\" is %c\n", j, argv[i], argv[i][j]);
j++;
}
}
}
else
fprintf(stderr,"Missing arguments\n");
return(EXIT_FAILURE);
return(EXIT_SUCCESS);
}
答案 2 :(得分:0)
代码:
#include <stdio.h>
#include <string.h>
const int num_chars = 3;
int main(int argc, char **argv) {
if(argc == 1) return 1;
if(num_chars <= 0) return 1;
for(int i=1; i<argc; i++)
{
if(num_chars > strlen(argv[i])) return 1;
printf("The first %d chars of %s is:\n", num_chars, argv[i]);
for(int j=0; j<num_chars; j++)
{
printf("%d = %c\n", j, argv[i][j]);
}
printf("\n");
}
return 0;
}
有效案例:
$ ./test hello world
The first 3 chars of hello is:
0 = h
1 = e
2 = l
The first 3 chars of world is:
0 = w
1 = o
2 = r
无效的情况:
$ ./test hel wo
The first 3 chars of hel is:
0 = h
1 = e
2 = l