2017-04-11 64 views
0

我試圖在C++中實現wc命令,但每當我嘗試運行該程序時都會發生終止(核心轉儲)錯誤。它編譯沒有錯誤,所以我不知道錯誤在哪裏。任何代碼風格的改進也將不勝感激。在wc程序中終止(核心轉儲)C++

#include <iostream> 
#include <string> 
#include <cstdlib> 
#include <string> 
#include <ctype.h> 
#include <unistd.h> 
#include <stdio.h> 

using namespace std; 
int main(int argc, char *argv[]) 
{                        
    setvbuf(stdout, NULL, _IONBF, 0); 
    int c_flag=0, l_flag=0, m_flag=0, w_flag=0; 
    int bytes; 
    int lines; 
    int characters; 
    int words; 
    int ch; 
    FILE *fp; 

    opterr = 0; 
    while((ch = getopt(argc, argv, "clmw::")) != 1) 
    { 
     switch (ch) 
     { 
      case 'c': 
       c_flag=1; 
       break; 
      case 'l': 
       l_flag=1; 
       break; 
      case 'm': 
       m_flag=1; 
       break; 
      case 'w': 
       w_flag=1; 
       break; 
      case '?': 
       fprintf(stderr, "wc: invalid option -- '%c'\nTry `wc --help' for more information.", optopt); 
       return EXIT_FAILURE; 
      default: 
       abort(); 
     } 
    } 
    if ((c_flag == 1) && (m_flag == 1)) 
    { 
     fprintf(stderr, "wc: cannot have both -c and -m flags\nTry `wc --help' for more information."); 
      return EXIT_FAILURE; 
    } 
    int i = optind; 
    if (i == optind) 
    { 
     printf("read stdin"); 
    } 
    else 
    { 
     for (int i = optind; i < argc; ++i) 
     { 
      string input; 
      input = string(argv[i]); 
      if (input == "-") 
      { 
       string buf; 
       char ch; 
       while(cin.get(ch)) 
       { 
        buf += ch; 
       } 
       printf("read stdin"); 
       if (c_flag) printf("c flag"); 
       if (l_flag) printf("l flag"); 
       if (m_flag) printf("m flag"); 
       if (w_flag) printf("w flag"); 
      } 
      else 
      { 
       fp = fopen(argv[i], "r"); 
       if (fp) 
       { 
        fseek(fp, 0L, SEEK_END); 
        bytes = ftell(fp); 
        rewind(fp); 
        while(!feof(fp)) 
        { 
         ch = fgetc(fp); 
         if (isspace(ch)) ++words; 
         while(isspace(ch)) 
         { 
          if(ch == '\n') ++lines; 
         } 
         ++characters; 
        } 
        printf("%d", lines); 
        printf("%d", words); 
        printf("%d", characters); 
        printf("%d", bytes); 
        if (c_flag) printf("c flag"); 
        if (l_flag) printf("l flag"); 
        if (m_flag) printf("m flag"); 
        if (w_flag) printf("w flag"); 
       } 
       else 
       { 
        fprintf(stderr, "wc: %s: No such file or directory ", argv[i]); return EXIT_FAILURE; 
       }      
      } 
     } 
    } 
    return EXIT_SUCCESS; 
} 
+3

你的調試器說了什麼?這是很多代碼讓人們猜測哪裏出了問題。調試器會完全告訴你**崩潰的位置。 – tadman

+0

僅供參考,這是C代碼,而不是C++ – Mikhail

+0

它使用了一些C++ - 字符串例如 – pm100

回答

0

您檢查getopt返回值時,有一個錯誤:

while((ch = getopt(argc, argv, "clmw::")) != 1) 

Per the function's specification,則返回-1時,有沒有更多的命令行參數來處理。由於這種無效狀況,您的switch屬於default並致電abort

+0

謝謝,這是有道理的,爲什麼它叫中止。 – Char