gpt4 book ai didi

c - 如何检查命令行参数中的最后一个字符?

转载 作者:行者123 更新时间:2023-11-30 19:32:40 27 4
gpt4 key购买 nike

所以我试图计算命令行中的文件数量,这是到目前为止我得到的

# include <stdio.h>
# include <stdlib.h>

int main(int argc, char* argv[]){
int cCount = 0;
int cHeadCount = 0;
int objCount = 0;
int makeCount = 0;
int othCount =0;

for(int i = 1; i< argc; i++){
/*
if argv[i] last char is c
cCount++;

if argv[i] last char is h
cHeadCount++;

and so on for the rest

*/
printf("C Source: %d\n", cCount);
printf("C Header: %d\n", cHeadCount);
printf("Object: %d\n", objCount);
printf("Make: %d\n", makeCount);
printf("Other: %d\n", othCount);
}

因此,如果您输入类似 $ ./fm main.c main.o sub.c sub.o 的内容你应该得到

C source: 2
C header: 0
Object: 2
Make: 0
Other: 0

我需要帮助的是 if for 循环内的语句。 BTW for 循环正确吗?有没有一个函数可以返回字符串的最后一个字符?据我所知,我似乎不记得了,但我可能是错的。

如果我的做法是错误的,或者是正确的,请告诉我。任何帮助表示赞赏。

编辑:

这是我在 for 里面的内容循环:

for(int i = 1; i < argc; i++){
int len = strlen (argv[i]);

if ((argv[i][len - 2] != '.') ){
if((strcmp(argv[i], "Makefile")==0) || (strcmp(argv[i], "makefile")==0)){
makeCount++;
}else{
othCount++;
continue; //if i take this out, it counts `other` objects wrong too
}
}

if(argv[i][len - 1] == 'c'){
cCount++;

}

else if(argv[i][len - 1] == 'h'){
cHeadCount++;

}

else if(argv[i][len - 1] == 'o'){
objCount++;

}

else {
othCount++;
}

}

所以现在的问题是它无法识别 makefile s 作为 Makefile。它将它们算作 Other 。所以我应该说 5 Makefile s 和 10 Other文件,它说我有 0 makefiles和 15 Other文件。 c , ho文件工作/计数良好。任何帮助表示赞赏

最佳答案

使用strrchr像这样

#include <stdio.h>
#include <string.h>

int main(int argc, char* argv[]){
int cCount, cHeadCount, objCount, makeCount, othCount;
cCount = cHeadCount = objCount = makeCount = othCount = 0;

for(int i = 1; i < argc; i++){
char *filename = strrchr(argv[i], '/');
filename = filename ? filename + 1 : argv[i];

char *ext = strrchr(filename, '.');
if(strcmp(filename, "Makefile") == 0 || strcmp(filename, "makefile") == 0){//or use strcasecmp ?
++makeCount;
} else if(ext == NULL) {
++othCount;
} else if(ext[1] == 'c' && ext[2] == 0){
++cCount;
} else if(ext[1] == 'h' && ext[2] == 0){
++cHeadCount;
} else if(ext[1] == 'o' && ext[2] == 0){//or strcmp(ext, ".o")==0
++objCount;
} else {
++othCount;
}
}
printf("C Source: %d\n", cCount);
printf("C Header: %d\n", cHeadCount);
printf("Object: %d\n", objCount);
printf("Make: %d\n", makeCount);
printf("Other: %d\n", othCount);
}

关于c - 如何检查命令行参数中的最后一个字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46822438/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com