指定一个文件夹,下面有许多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,统计正确。