博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
函数式C代码
阅读量:6720 次
发布时间:2019-06-25

本文共 2377 字,大约阅读时间需要 7 分钟。

代码如下:

#include 
#include
typedef char String[32];typedef FILE* File;typedef struct _Employee { String name; int age; int salary; struct _Employee *next;} *Employee;typedef void (*Callback)(Employee);/* High Order Functions */void foreach(Employee e, Callback fn) { Employee p; while (p = e) { e = e->next; /* Avoid *next be changed in fn */ fn(p); }}void with_open_file(String filename, String mode, Callback fn, Employee e) { File file = freopen(filename, mode, (mode[0] == 'r'? stdin: stdout)); if (file == NULL) { fprintf(stderr, "Cannot open %s with %s mode.\n", filename, mode); exit(EXIT_FAILURE); } fn(e); fclose(file);}/* Destructor */static void employee_free_node(Employee e) { if (e != NULL) { free(e); }}void employee_free(Employee e) { foreach(e, employee_free_node);}/* Input */static void employee_read_node(Employee node) { Employee e = NULL, *head = (Employee*) node; e = *head = (Employee)calloc(1, sizeof(struct _Employee)); if (e != NULL && scanf("%s%d%d", e->name, &e->age, &e->salary) != 3) { employee_free(e); *head = NULL; }}void employee_read(Employee list) { Employee e = NULL, *head = (Employee*) list, tail = NULL; *head = NULL; while (employee_read_node((Employee)&e), e) { if (*head != NULL) { tail->next = e; tail = e; } else { *head = tail = e; } }}/* Output */static void employee_print_node(Employee e) { printf("%s %d %d\n", e->name, e->age, e->salary);}void employee_print(Employee e) { foreach(e, employee_print_node);}/* Business Logic */static void employee_adjust_salary_node(Employee e) { if (e->salary < 30000) { e->salary += 3000; }}void employee_adjust_salary(Employee e) { foreach(e, employee_adjust_salary_node);}int main(void) { Employee e = NULL; with_open_file("work.txt", "r", employee_read, (Employee)&e); employee_print(e); employee_adjust_salary(e); employee_print(e); with_open_file("work.txt", "w", employee_print, e); employee_free(e); return EXIT_SUCCESS;}

work.txt

William 35 28000Kishore 41 35000Wallace 37 23000Bruce 39 18000

转载于:https://www.cnblogs.com/code-style/p/3286984.html

你可能感兴趣的文章
滴滴发布2018年度总结:又有网友炸锅了
查看>>
PCB画板软件那么多,我到底该学习哪一个?
查看>>
linux创建用户与用户组
查看>>
如何从Spotify Music中删除DRM?
查看>>
VR开发者为Labo VR辩护 预计这可能是任天堂进军VR的开始
查看>>
全面解析大数据框架Hadoop主要模块
查看>>
手写调用门
查看>>
海恩法则与墨菲定律
查看>>
linux RHEL 解决中文网页乱码和界面英文
查看>>
linux中oracle的日常维护命令
查看>>
Linux 修改IP地址和网关
查看>>
linux查看硬件信息
查看>>
apache http的源码编译
查看>>
find命令的参数
查看>>
H3C交换机配置镜像端口
查看>>
ESXI6.0(6.7)实践——惠普A6 7310主板,APU,Realtek网卡的安装之路
查看>>
我的友情链接
查看>>
26期学员参观森华易腾移动IDC机房有感
查看>>
三、一个简单的BDB JE例子
查看>>
在Windows Server2008R2安装Oracle Database 11g Release 2
查看>>