wc.txt

来自「Linux环境下的简单的shell编程 用C模拟」· 文本 代码 · 共 70 行

TXT
70
字号
#include <unistd.h>
#include <stdio.h>
#include <string.h>
#include <sys/stat.h>
#include <stdlib.h>
#include <sys/types.h>
#include <dirent.h>
#include "ourhdr.h"
#include <fcntl.h>

int main(int argc, char *argv[])
{
	struct stat statbuf;		//the buffer stored file state
	FILE * filestream;		//temp file stream
	int filedescriptor;		//temp file descriptor
	char buffer[1];		//the buffer stored the bytes in file
	int i, j;
	for (i = 1; argv[i] != NULL; i++)	//support parameters which are more the one

	{
		int bcount = 0;	//the number of bytes in files
		int wcount = 0;	//the number of words in files
		int lcount = 0;	//the number of lines in files

		if ( (j = lstat(argv[i], &statbuf)) == -1)	//if the parameter is a directory

		{
			printf("The file or directory does not exist\n");
			exit(0);
		}
		if (S_ISDIR(statbuf.st_mode))
		{
			printf("wc %s: is a directory\n", argv[i]);
			printf("byte: 0    word: 0    line: 0 /\n");
			continue;
		}		
	
		filedescriptor = open(argv[i], O_RDONLY);	//count the number of lines
		while (read (filedescriptor, buffer, 1) != 0)
		{
			if (buffer[0] == '\n')
				lcount++;
		}
		printf("line: %d    ", lcount);
		close(filedescriptor);

		filedescriptor = open(argv[i], O_RDONLY);	//count the number of words		
		while (read (filedescriptor, buffer, 1) != 0)
		{
			if (buffer[0] == ' ' || buffer[0] == '\n')
				wcount++;
		}
		printf("word: %d    ", wcount);
		close(filedescriptor);

		filestream = fopen(argv[i], "r");	//count the number of bytes
		while (fgetc(filestream) != EOF)
		{
			bcount++;
		}
		printf("byte: %d    ", bcount);
		if (argc != 2)
			printf("%s\n", argv[i]);
		else
			printf("\n");
		fclose (filestream);
	}
	exit(0);
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?