C/C++中计算字符串数组长度方法:
int len = sizeof(array)/sizeof(array[0])
注意:字符串数组作为擦参数传递给其他函数时,对方函数中sizeof(array)返回值始终未4,
所以,如果一定要通过函数处理数组时,必须把数组长度一起传过去
int size = sizeof(ignore_file_names);
int firstSize = sizeof(ignore_file_names[0]);
int len = size/firstSize;
//hulk: is_ignore_complete_file_name: size: 12, firstSize: 4, length: 3
hulk_trace("hulk: is_ignore_complete_file_name: size: %d, firstSize: %d, length: %d", size, firstSize, len);
举个栗子
/**
* 是否为需要忽略的完整文件名
* @param file_name
* @return true
* @return false
*/
bool is_ignore_complete_file_name(const char *file_name) {
if(file_name == NULL || *file_name == 0){
return false;
}
hulk_trace("hulk: is_ignore_complete_file_name: Dest file_name: %s", file_name);
//需要忽略的文件名数组
char *ignore_file_names[] = {"vpncore.log", "trustcore.log", "timerslack_ns"};
//C/C++中计算字符串数组长度方法:int len = sizeof(array)/sizeof(array[0])
//注意:字符串数组作为擦参数传递给其他函数时,对方函数中sizeof(array)返回值始终未4,
//所以,如果一定要通过函数处理数组时,必须把数组长度一起传过去
int size = sizeof(ignore_file_names);
int firstSize = sizeof(ignore_file_names[0]);
int len = size/firstSize;
//hulk: is_ignore_complete_file_name: size: 12, firstSize: 4, length: 3
hulk_trace("hulk: is_ignore_complete_file_name: size: %d, firstSize: %d, length: %d", size, firstSize, len);
int i=0;
char *element;
do
{
if (i >= len){
//防止溢出
hulk_trace("hulk: is_ignore_complete_file_name: Invalid i: %d", i);
break;
}
element = ignore_file_names[i];
if (element != NULL && *element != 0){
//hulk_trace("hulk: is_ignore_complete_file_name: element: %s", element);
//strcmp返回值:
//如果返回值 < 0,则表示 str1 小于 str2
//如果返回值 > 0,则表示 str2 小于 str1
//如果返回值 = 0,则表示 str1 等于 str2
int res = strcmp(file_name, element);
bool equals = res == 0;
if (equals){
//hulk_trace("hulk: is_ignore_complete_file_name: found element: %s", element);
return true;
}
} else {
hulk_trace("hulk: is_ignore_complete_file_name: Invalid file array element: %s", element);
}
i++;
} while (i < len);
//未找到
return false;
}