操作系统:shell程序统计C文件中系统函数调用次数(含代码)

该博客介绍了如何编写一个Shell脚本来统计指定文件夹下C源程序文件中系统调用如printf、open、close等的使用次数。通过循环遍历C文件并使用grep命令进行关键词计数,最终结果被整理成表格形式并保存到output.txt文件中。示例运行结果显示,脚本正确统计了各文件中关键词的出现次数,并与源代码进行了对比验证,证实统计准确。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


指定一个文件夹,下面有许多C源程序文件。按要求编写一个shell程序,分别统计每个C文件中printf、open、close、read、write、fork、signal系统函数被调用的次数,并将统计结果保存到一个文件中。


1、原理说明

按照解题思路编写代码就行。

2、代码说明

以下说明关键代码:

1、只看C源程序文件

for file in ${folder}/*.c
do

done

${folder}/*.c代表folder这个目录下的以.c结尾的文件。

2、统计C文件file中关键词key的出现次数

grep -o $key $file |wc -l

所以只要循环执行这个语句,并把结果存入一个TXT文件即可得到每个文件中每个关键词出现的次数。

3、在文件中构建一个表,横坐标代表关键字key,纵坐标代表文件file。

首先构建表头,表头应该是纵坐标文件file。

for file in ${folder}/*.c
do
filename=`basename $file`
echo -e -n “\t” >>./output.txt
echo -n $filename >>./output.txt
done
echo ‘’ >>./output.txt

-e的意思是启动转义字符。
-n的意思是不换行。

然后循环一行一行地填入每个关键字key的出现次数。

for key in ${keys[@]}
do
find key
done

key作为参数传递给find函数,find的作用就是打印每个文件file中key的出现次数,详见源代码。

3、运行结果

1、首先看一下prg/cfile中,既有C语言文件,也有其它类型的文件

czxt2022@ubuntu:~$ ls prg/cfile
4-1.c 4-2.c 4-3.c 4-4.c 4-5.c 4-6.c 4-7.c c1 c1.c res.txt ts.txt

2、运行shell文件

czxt2022@ubuntu:~$ ./4.sh
请输入文件夹地址:
prg/cfile
统计完毕!

3、查看输出文件output.txt,只统计了C语言文件

czxt2022@ubuntu:~$ cat output.txt
4-1.c 4-2.c 4-3.c 4-4.c 4-5.c 4-6.c 4-7.c c1.c
printf 7 1 2 2 3 6 3 10
open 0 2 2 2 2 0 0 4
close 0 2 3 1 1 0 0 3
read 0 1 0 1 0 0 0 7
write 0 1 0 0 1 0 0 1
fork 0 0 0 0 0 3 0 1
signal 0 0 0 0 0 0 7 1

4、看一下4-1.c和4-2.c的源代码,看看是否统计正确

czxt2022@ubuntu:~$ cat prg/cfile/4-1.c
#include <stdio.h>
int main()
{
char ch = ‘A’;
char str[20] = “www.runoob.com”;
float flt = 10.234;
int no = 150;
double dbl = 20.123456;
printf(“字符为 %c \n”, ch);
printf(“字符串为 %s \n” , str);
printf(“浮点数为 %f \n”, flt);
printf(“整数为 %d\n” , no);
printf(“双精度值为 %lf \n”, dbl);
printf(“八进制值为 %o \n”, no);
printf(“十六进制值为 %x \n”, no);
return 0;
}

只有7个printf,统计正确。

czxt2022@ubuntu:~$ cat prg/cfile/4-2.c
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
main()
{
int fd, size;
char s[] = “Linux Programmer!\n”, buffer[80];
fd = open(“/tmp/temp”, O_WRONLY|O_CREAT);
write(fd, s, sizeof(s));
close(fd);
fd = open(“/tmp/temp”, O_RDONLY);
size = read(fd, buffer, sizeof(buffer));
close(fd);
printf(“%s”, buffer);
}

1个printf、2个open、2个close、1个read、一个write,统计正确。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

俊夫小瞳

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值