linux下wc功能的簡單實現


1.代碼來源:自己編寫

2.運行環境:linux終端

3.編程語言:c/c++語言

4.bug:未發現

5.當前功能:可以統計字符的字符數、行數、單詞數

6.使用方法:wc -l 文件名-->統計行數、wc -w 文件名-->統計但詞數、wc -c 文件名-->統計字符數

7.gitbub代碼地址:https://github.com/moonzhu/wc

8.實現:

/*
* WC.h
*
* Created on: Sep 9, 2017
* Author: moon
*/

#ifndef WC_H_
#define WC_H_
#include <string>

class WC {
public:
WC();
virtual ~WC();
private:
std::string fileName;
public:
/**
* @function:Setting value of fileName
*/
void setFileName(std::string fileName);
/**
* @function:Counting the number of character
* @return:If success,return the number of character,else return -1
*/
int computingChar(void);
/**
* @function:Counting the number of word
* @return:If success,return the number of word,else return -1
*/
int computingWord(void);
/**
* @function:Counting the number of line
* @return:If success,return the number of line,else return -1
*/
int computingLine(void);
};

#endif /* WC_H_ */

 

/*
* WC.cpp
*
* Created on: Sep 9, 2017
* Author: moon
*/

#include "WC.h"
#include <fstream>
using namespace std;

WC::WC() {
}

WC::~WC() {
}

void WC::setFileName(string fileName) {
this->fileName = fileName;
}

int WC::computingChar(void) {
std::ifstream in(fileName);
if (!in.is_open())
return 0;

in.seekg(0, std::ios_base::end);
std::streampos sp = in.tellg();
in.close();
return sp;
}

int WC::computingLine(void) {
ifstream in;
int num = 0;
string str;

in.open(fileName);
while (getline(in, str)) {
num++;
}
in.close();
return num;
}

int WC::computingWord(void) {
int num = 0;
char c;
char priorC;
ifstream in;

in.open(fileName);
in.get(c);
priorC = ' ';
while (!in.eof()) {
if (c >= 'a' && c <= 'z') {
if (priorC == ' ' || priorC == '\n' || priorC == '.'
|| priorC == ',' || priorC == ':' || priorC == '?'
|| priorC == '!') {
num++;
}
}

priorC = c;
in.get(c);
}
in.close();
return num;
}

 

//============================================================================
// Name : wc.cpp
// Author :
// Version :
// Copyright : Your copyright notice
// Description : Hello World in C++, Ansi-style
//============================================================================

#include <iostream>
#include "WC.h"
#include <string.h>
using namespace std;

int main(int argc, char **argv) {
WC wc;

if (argc < 3)
return -1;
string fileName(argv[2]);
wc.setFileName(fileName);
if (strcmp(argv[1], "-c") == 0) {
cout << wc.computingChar() << endl;
} else if (strcmp(argv[1], "-w") == 0) {
cout << wc.computingWord() << endl;
} else if (strcmp(argv[1], "-l") == 0) {
cout << wc.computingLine() << endl;
} else if (strcmp(argv[1], "-s") == 0) {

}

return 0;
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM