该楼层疑似违规已被系统折叠 隐藏此楼查看此楼
该程序用于实现linux系统中wc命令的最简单模式
wc 命令用于统计文件中字符信息。
[xx@localhost 1.5]$ wc 01.c 02.c 03.c
15 23 131 01.c
13 18 127 02.c
14 20 128 03.c
42 61 386 总用量
使用c语言写出这种小程序。
/*
* Name: count.c
* Title: the number of line, word, characters in file
* Descripts: count the number of line, word, characters in file
* Author: lnesuper
* Copyrighte: GPL
* Date: 2015.5.25
* Use: count [file1] [file2]...
*/
#include
#include
#define IN 1 /* inside a word */
#define OUT 0 /* outside a word */
int main(int argc, char * argv[])
{
if (argc == 1) {
printf("\aUsing: count [file1] [file2]...\n");
exit(EXIT_FAILURE);
}
int c, nl, nw, nc, state; /* line, word, character */
int nl_total, nw_total, nc_total;
nl_total = nw_total = nc_total = 0;
int n;
for (n = 1; n < argc; n++) {
FILE * file = fopen(argv[n], "r");
if (file == NULL) {
printf("Can't open file %s\n", argv[n]);
exit(EXIT_FAILURE);
}
nl = nw = nc = 0;
state = OUT;
while ((c = fgetc(file)) != EOF) {
++nc;
if (c == '\n')
++nl;
if (c == ' ' || c == '\t' || c == '\n')
state = OUT;
else if (state == OUT) {
++nw;
state = IN;
}
}
nl_total += nl;
nw_total += nw;
nc_total += nc;
printf("%d %d %d %s\n", nl, nw, nc, argv[n]);
fclose(file);
}
// printf("total information:\n");
printf("%d %d %d total\n", nl_total, nw_total, nc_total);
return 0;
}
linux下编译运行结果
gcc -Wall -o count count.c
[lhf@localhost 1.5]$ ./count 01.c 02.c 03.c
15 23 131 01.c
13 18 127 02.c
14 20 128 03.c
42 61 386 total
[lhf@localhost 1.5]$ wc 01.c 02.c 03.c
15 23 131 01.c
13 18 127 02.c
14 20 128 03.c
42 61 386 总用量
可以看出与wc命令结果一致。