在C语言中,我经常希望以相同的方式处理从文件读取的数据和从字符串数组读取的数据。通常,从文件中读取是为了生产用途,而从字符串中读取是为了测试用途。我最终编写了很多像这样的代码:
void handle_line(char *line, Things *things) {
...
}
Things *read_from_chars(char *lines[]) {
Things *things = Things_new();
for (int i = 0; lines[i] != NULL; i++) {
handle_line(lines[i], things);
}
return things;
}
Things *read_from_input(FILE *input) {
char *line = NULL;
size_t linelen = 0;
Things *things = Things_new();
while (getline(&line, &linelen, input) > 0) {
handle_line(line, things);
}
return things;
}
这是一种重复劳动。
有没有办法让字符串数组伪装成FILE *
指针?反之亦然?或者有没有更好的模式来处理这个问题?
额外加分:解决方案应该使char *
或char **
可用于标准文件函数,如fgets
和getline
。
handle_line
中,而两个函数read_from_chars
和read_from_input
执行两个不同的任务(实际上是你需要支持的两个任务)。这将是问题的正常解决方案。更复杂的方法是处理函数在需要一行时调用回调来读取一行。 - M.Mread_from_chars
和read_from_input
是重复劳动。它们在概念上都做相同的事情:初始化输出变量,为每行调用回调函数。 - Schwern