C语言中使用类似awk的功能

awk实在是太强大了, 非常复杂的任务,几行代码就可以解决, awk经常需要用到, 但是在c语言里面, 调用system不太优雅, 能不能直接在c语言中直接调用呢,简单实现了一些功能, 但大多数情况,够用了,参考

https://github.com/yiifburj/my_tools/blob/master/simple_use_of_awk_in_c.c

后面有一个示例, 可以参考, 使用方法主要是 填写

struct awk_st
{
#define PATTERN_NUM 3
#define PATTERN_SIZE 16
    int pattern_num;
    char pattern[PATTERN_NUM][PATTERN_SIZE];
    awk_begin_t fun_begin;
    awk_end_t fun_end;
    char action_default[0];
    awk_action_t actions[PATTERN_NUM];
    char data[0];
};

 pattern可以不写, 但至少写一个action,除非不需要, 多个pattern的时候个数要和action保持一致并且一一对应,同时要设置 pattern_num, pattern使用POSIX Extended Regular Expression , fun_begin fun_end fun_action都需要自己实现, 可以为NULL, data[0]指向的部分会被传入到fun_begin fun_end fun_action中.

同时提供了字符串替代函数

/* not found also return 0 */
int awk_str_replace_inplace(char *src, const char *old, const char *new);
int awk_str_replace(const char *src, const char *old, const char *new, char buf[], int bufsize);
int awk_str_replace_regex(const char *src, const char *pattern, const char *new, char buf[], int bufsize);
int awk_str_replace_regex_inplace(char *src, const char *pattern, const char *new);
失败返回负数

详情参考代码。

原文地址:https://www.cnblogs.com/yiifburj/p/7822683.html