对于教育用途,我试图实现一个简单的查找程序(类似于find(1),功能少得多)。
在实施第一个功能时 - " -user" - 我通过将两个不同的函数(一次用于uid,一次用于名称)与一个"控制函数组合来进行挑战?"。我想我正在寻找像C#中的重载函数类似的东西,在C中解决这样一个问题的最佳实践是什么?
我很感激一种解决方案,它允许我的程序在调用时处理这两个选项: E.g:
如果您在我的样本中发现了一些编码或样式问题,请指出它们,我愿意学习!我知道错过了一些干净的内存管理,但稍后会添加它。
更新 我正在考虑一个函数,它将参数作为一个char数组处理,并检查每个char的ASCII码并调用该函数,如果没有" char"被找到。类似的东西"合法的"?
#include <dirent.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <stdlib.h>
#include <pwd.h>
void entries_with_uid(char *init_path, int pattern_uid);
void entries_with_name(char *init_path, char *pattern_name);
int main(int argc, char **argv)
{
/*
char *path = argv[1];
*/
entries_with_name("/home/mario/Documents/codes", "mario");
entries_with_uid("/home/mario/test_project", 1000);
return 0;
}
void entries_with_uid(char *init_path, int pattern_uid)
{
DIR *dir;
struct dirent *entry;
dir = opendir(init_path);
entry = readdir(dir);
if(dir == NULL) return;
if(entry == NULL) return;
do {
if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0) continue;
char path[1024];
int len = snprintf(path, sizeof(path)-1, "%s/%s", init_path, entry->d_name);
path[len] = 0;
struct stat sb;
stat(path, &sb);
if(sb.st_uid == pattern_uid) printf("%s\n", path);
if (entry->d_type == DT_DIR) entries_with_uid(path, pattern_uid);
} while (entry = readdir(dir));
closedir(dir);
}
void entries_with_name(char *init_path, char *pattern_name)
{
DIR *dir;
struct dirent *entry;
dir = opendir(init_path);
entry = readdir(dir);
if(dir == NULL) return;
if(entry == NULL) return;
do {
if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0) continue;
char path[1024];
int len = snprintf(path, sizeof(path)-1, "%s/%s", init_path, entry->d_name);
path[len] = 0;
struct stat sb;
stat(path, &sb);
struct passwd *pwd = getpwuid(sb.st_uid);
if(strcmp(pwd->pw_name, pattern_name) == 0) printf("%s\n", path);
if (entry->d_type == DT_DIR) entries_with_name(path, pattern_name);
} while (entry = readdir(dir));
closedir(dir);
}
谢谢!
更新
我用一个在参数中检查字母数字字符串的函数解决了问题:
int count_alphanumeric(char *string)
{
int alphanumeric_counter = 0;
int i = 0;
while(string[i]!='\0')
{
if (string[i] <= 57 && string[i] >= 48)
{
i++;
continue;
}
else alphanumeric_counter++;
i++;
}
return alphanumeric_counter;
}
仍在寻找更优雅的选择! ;)
Cheeers!
答案 0 :(得分:1)
您需要检查用户键入的字符串是否为数字。这与函数重载或任何此类语法糖无关。函数重载基于编译时已知的类型,而不是用户可以键入的内容,因此不要寻找一种巧妙的方法来使用它。你目前的想法绝对没问题。
然而,实施并非如此。到底是什么57?为什么要记住ASCII表?字符常量用单引号书写,例如'0'和'9'。为什么要重新发明轮子?废弃并使用正确的惯用C方式。
int is_numeric (const char* s, unsigned long* number_return)
{
char* endp;
*number_return = strtoul(s, &endp, 0);
return (*endp == '\0');
}