c语言 计算从1加到50,C语言非常简单的字符统计程序50行

该楼层疑似违规已被系统折叠 隐藏此楼查看此楼

该程序用于实现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命令结果一致。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值