加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
wc.cpp 2.95 KB
一键复制 编辑 原始数据 按行查看 历史
hy 提交于 2018-09-15 03:16 . new
#include<stdio.h>
#include<ctype.h>
#include<stdbool.h>
#include<stdlib.h>
#include<unistd.h>
int main(int argc,char *argv[])
{
char ch;
int choice;
FILE *fp;
unsigned long lines=1;//行数
unsigned long count=0;//字符数
int n_words=0;//单词数
bool inword=false;//一个flag,如果c在单词中,inword等于true
unsigned long cd_lines=0;//代码行数
unsigned long e_rows=0;//空行数
unsigned long cm_lines=0;//注释行数
while((choice=getopt(argc,argv,"c::w::l::a"))!=-1){
switch(choice){
case 'c':{
if(argc!=3){
printf("Usage: %s filename\n",argv[0]);
exit(EXIT_FAILURE);}
if((fp=fopen(argv[2],"r"))==NULL)
{
printf("Can't open %s\n",argv[2]);
exit(EXIT_FAILURE);
}
while((ch=getc(fp))!=EOF)
{
count++;
}
fclose(fp);
printf("File %s has %lu characters\n",argv[2],count);
break;
}
case 'w':{
if(argc!=3){
printf("Usage: %s filename\n",argv[0]);
exit(EXIT_FAILURE);
}
if((fp=fopen(argv[2],"r"))==NULL){
printf("Can't open %s\n",argv[2]);
exit(EXIT_FAILURE);
}
while((ch=getc(fp))!=EOF){
if(!isspace(ch)&&!ispunct(ch)&&!inword){//若c不为空格,不为标点符号,不在单词中
inword=true;
n_words++;
}
if(inword&&(isspace(ch)||ispunct(ch)))//若c不在单词中,是空格或者标点符号
inword=false;
}
fclose(fp);
printf("File %s has %d words\n",argv[2],n_words);
break;
}
case 'l':{
if(argc!=3){
printf("Usage: %s filename\n",argv[0]);
exit(EXIT_FAILURE);
}
if((fp=fopen(argv[2],"r"))==NULL)
{
printf("Can't open %s\n",argv[2]);
exit(EXIT_FAILURE);
}
while((ch=getc(fp))!=EOF)
{
if(ch=='\n'||ch=='\0')lines++;
}
fclose(fp);
printf("File %s has %lu lines\n",argv[2],lines);
break;
}
/* case 'a':{
if(argc!=3){
printf("Usage: %s filename\n",argv[0]);
exit(EXIT_FAILURE);
}
if((fp=fopen(argv[2],"r"))==NULL){
printf("Can't open %s\n",argv[2]);
exit(EXIT_FAILURE);
}
//方法一
char arr[100];
ch=getc(fp);
while (ch!= EOF){
if(ch=='\n'){
int i=0;
ch=getc(fp);
while(ch!='\n'){
arr[i]=ch;
i++;
}
if(strlen(arr)<2)e_rows++;
}
else if(ch=='{'||ch=='}'){
ch=getc(fp);
if(ch=='\n')e_rows++;
}
else {
cd_lines++;
while (ch != '{'&&ch != '}'&&ch != '\n'&&ch != '/'&&ch != EOF)
{
ch = getc(fp);
}
}
}//空格不会弄
//方法二 代码行与空行的判断
char st[100];
while(!feof(fp)){
int show_char=0;
int i=0;
if(fgets(st,sizeof(st),fp)){
for(i=0;i<strlen(st);i++)
{
if(st[0]=='\n'){
e_rows++;
break;
}
else if(st[i]=='\0'||(st[i]=='{'&&st[i+1]=='\0')||(st[i]=='}'&&st[i+1]=='\0')){
e_rows++;
break;
}
}
}
else if (ch == '/')
{
ch = getc(fp);
if (ch == '/')
while (ch != '\n')
{
ch = getc(fp);
}
cm_lines++;
ch = getc(fp);
}
}
}*/
return 0;
}
}
}
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化