Words and Lines Counting Utility

Environment: VC6, MFC

This utility is very useful for counting the number of lines and words in programs or text files. The utility is very simple but it is also very powerful. You can find any group of files and see through the list and check out the number of words and lines in a group of files. This was the kind of utility that I was wanting for a long time and I finally wrote it.

First, it has a dialog-based interface and it has numerous descriptive fields that you may find very useful as you start using it. The utility operates in a single thread and does PeekMessage to do GUI tasks, as shown in the following snippet of code:

MSG Msg;
if(::PeekMessage(&Msg, m_hWnd, WM_NULL, WM_USER-1, PM_NOREMOVE)){
   ::PeekMessage(&Msg, m_hWnd, WM_NULL, WM_USER-1, PM_REMOVE);

This dispatches any pending messages to the main window, thus not blocking. This is because the MFC classes cannot be exported to a different thread and it gives lots of problems, as I've observed in many of my utilities.

First, the directory where the files have to be counted is to be mentioned in the edit box provided. The Browse button will open the shell dialog box for directory browsing; this is implemented in the following piece of code:

BOOL ShellGetPathCount(HANDLE hDlg, char lpszPath[])
  BOOL bRet;
  char szPath[MAX_PATH];
  HGLOBAL hgMem;

  bi.hwndOwner=(HWND) hDlg;
  bi.pidlRoot = NULL;
  bi.pszDisplayName = szPath;
  bi.lpszTitle = "Select Destination Folder";
  bi.lpfn = NULL;
  bi.lParam = 0L;
  bi.iImage = 0;
  lpil = SHBrowseForFolder(&bi);
  if(lpil == NULL)
    return FALSE;
  bRet = SHGetPathFromIDList(lpil, lpszPath);
  hgMem = GlobalHandle(lpil);
  return bRet;

The above code gets the path from the ID list and gives the caller the path. Then it frees the memory associated with the list. It fills a structure and passes it to the shell API that displays the dialog. If OK is clicked, it gets the directory from the list and returns the directory to the caller. It can be any directory that is browsible using Explorer.

Then, after the "Start Count" button is clicked, it starts the following routine that does the work of counting the lines and words in the filespecs provided in the next edit box. The filespecs can contain multiple filespecs such as *.C;*.CPP;*.txt without any spaces in between them. This counts the files in that directory with those filespecs. You can also put in individual files such as RFC.TXT, and so forth, which are ; delimeted.

void CWordLineDlg::OnCount()
  // TODO: Add your control notification handler code here
  char Directory[MAX_PATH], FileSpecs[300], TmpStr[MAX_PATH],
  int NumFileSpecs=0, NumWords=0, NumLines=0;
  Stop = false;

  m_Specs.GetWindowText(FileSpecs, 290);
  m_Dir.GetWindowText(Directory, MAX_PATH);
    AfxMessageBox("Directory not found");
    strcat(Directory, "\\");
    if(*(TmpVal++) == ';'){
    AfxMessageBox("Directory not found");
    AfxMessageBox("Filespec not found");
  for(int i=0; i<NumFileSpecs; i++){
    strcpy(TmpStr, Directory);
    char TmpStr1[5]={0, 0};
      if(*(TmpVal++) != ';'){
        strcat(TmpStr, TmpStr1);
    struct _finddata_t ff;
    long hFind = _findfirst(TmpStr, &ff);
    while(strcmp(ff.name, ".")==0 || strcmp(ff.name, "..")==0)
      _findnext(hFind, &ff);
      HANDLE hFile = CreateFile(ff.name, GENERIC_READ, NULL, NULL,
                                FILE_ATTRIBUTE_NORMAL, NULL);
      NumWords = CountWords(hFile);
      SetFilePointer(hFile, 0, 0, FILE_BEGIN);
      NumLines = CountLines(hFile);
      m_List.InsertItem(0, ff.name);
      char TmpStr2[20];
      wsprintf(TmpStr2, "%u", NumWords);
      m_List.SetItemText(0, 1, TmpStr2);
      wsprintf(TmpStr2, "%u", NumLines);
      m_List.SetItemText(0, 2, TmpStr2);
      MSG Msg;
      if(::PeekMessage(&Msg, m_hWnd, WM_NULL, WM_USER-1,
        ::PeekMessage(&Msg, m_hWnd, WM_NULL, WM_USER-1, PM_REMOVE);
    }while(!_findnext(hFind, &ff));
  long Tmp;
  OnItemchangedFilelist(NULL, &Tmp);

The files are searches from the first filespec fully in the directory and followed by the next one in the list. Then, after the files have been found, selected files are listed with the number of words and lines in the box provided beneath the list view. This way, you can easily see the number of words and lines found in specific files alone and you can watch specific text or program files.

The routine that groups the files marked is provided below. It calculates this information every time the files in the list are being touched.

void CWordLineDlg::OnItemchangedFilelist(NMHDR* pNMHDR,
                                         LRESULT* pResult)
  // TODO: Add your control notification handler code here
  int NumWords=0, NumLines=0, MarkedLines=0, MarkedWords=0,
  char TmpStr[100];
  for(int i=0; i<m_List.GetItemCount(); i++){
    m_List.GetItemText(i, 1, TmpStr, 20);
    NumWords += atoi(TmpStr);
    m_List.GetItemText(i, 2, TmpStr, 20);
    NumLines += atoi(TmpStr);
    if(m_List.GetItemState(i, LVIS_SELECTED)==LVIS_SELECTED){
      m_List.GetItemText(i, 1, TmpStr, 20);
      MarkedWords += atoi(TmpStr);
      m_List.GetItemText(i, 2, TmpStr, 20);
      MarkedLines += atoi(TmpStr);
      wsprintf(TmpStr, "%u", MarkedWords);
      wsprintf(TmpStr, "%u", MarkedLines);
      wsprintf(TmpStr, "%u", NumMarkedFiles);
  wsprintf(TmpStr, "%u", NumWords);
  wsprintf(TmpStr, "%u", NumLines);
  wsprintf(TmpStr, "%u", m_List.GetItemCount());

  *pResult = 0;

When an item changes its selection state, the notification handler calls the preceding routine. When it gets activated, it calculates the total marked files and displays the information accordingly.


Download source - WordLine.zip 12 Kb

About the Author

Vinoj Kumar

I have been programming for the past 16 years. I started programming in 1990. I came to Windows in 1993. I have authored a book called, "Classic Utilities Using Assembly Language" , 1995. In my free time I listen a lot to Kenny G sax all the albums and Valentine Classics Songs. I like to watch a lot of TinTin adventure Comics. I am currently working in K7 Computing antivirus company (www.k7computing.com) as Senior Technical Lead. My contact is: Phone: +91 944 411 7353


  • Excellent!

    Posted by Legacy on 03/07/2003 12:00am

    Originally posted by: Raj

    It is a very good program and excellet work there.

  • Words and Lines Counting Utility

    Posted by Legacy on 11/27/2002 12:00am

    Originally posted by: Mamtha Ragupathy

    That was a Wonderful Article. Very Helpful!!! Thanks Vinoj Kumar.

  • Reinventing

    Posted by Legacy on 08/30/2002 12:00am

    Originally posted by: Andrey Koubychev

    Day by day I see CodeGuru and CodeProject authors reinventing old UNIX programs :)

  • Give peace a chance ...

    Posted by Legacy on 08/30/2002 12:00am

    Originally posted by: Christiaan

    Criticasters should spend more time to contribute themselves, assuming that their contribution contains at least one headline that is worth to be revealed ( which is the case with this article ) ...

  • I don't get it?

    Posted by Legacy on 08/30/2002 12:00am

    Originally posted by: Hector

    First, its slow. Why have two separate functions to CountWords() and then file reset to CountLines()? Why not do it at the same time? Also Read by 1 byte at a time? Ouch! You can speed up this program tremendously!

    Second, I believe the word count is off by one.

    Third, the only thing I see useful if your dialog "file processor". There is more worthiness in this.

    Separate your "file processor" functions into their own files and then place a stub for "ProcessFiles(filename)"

    then your dialog can be used for many things.

Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • Rocket Mobile® for IBM i is an enterprise mobile application development and deployment platform for customers who rely on the IBM i system. Rocket Mobile for IBM i enables customers to leave proven applications in-place and rapidly repurpose them into new managed and secure mobile applications. Fast, easy creation of mobile, web, and hybrid mobile applications that deploy to any iOS, Android, or Windows mobile phone or tablet Built-in integration for seamless repurposing of existing IBM i applications …

  • Complex hybrid environments can make it difficult to track interdependencies, increasing the risk of disrupting critical business services. In this white paper by EMA, you'll learn how application discovery and dependency mapping can help you: Meet granular targets for availability, cost, and time-to-revenue for cloud services. Accelerate mean time to repair (MTTR) while communicating better with stakeholders. Manage even the most complex hybrid environments more efficiently and effectively Understand the …

Most Popular Programming Stories

More for Developers

RSS Feeds

Thanks for your registration, follow us on our social networks to keep up-to-date