Advertisement
Guest User

Untitled

a guest
May 27th, 2011
107
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.80 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4.  
  5. #define MAX_LINE_LEN 100
  6. #define MAX_WORDS 100
  7. #define DELIMITERS "- ,.!?:;*()\n\t"
  8.  
  9. char *mystrdup(const char *src);
  10. int exist(char *list[], int list_num, const char *word);
  11.  
  12. int main(int argc, char *argv[]){
  13.     FILE *fp;
  14.     char buf[MAX_LINE_LEN];
  15.     char *found_words[MAX_WORDS];
  16.     int found_word_cnt = 0;
  17.     char *token;
  18.     int token_len;
  19.    
  20.     /* 入力エラー */
  21.     if(argc != 2){
  22.         fprintf(stderr, "usage: %s input_file_name\n", argv[0]);
  23.         exit(1);
  24.     }
  25.    
  26.     if( (fp=fopen(argv[1], "r")) == NULL ){
  27.         fprintf(stderr, "error: invalid filename input\n");
  28.         exit(1);
  29.     }
  30.    
  31.     while(fgets(buf,MAX_LINE_LEN,fp) != NULL){
  32.         token = strtok(buf,DELIMITERS);
  33.         while(token != NULL){
  34.             token_len = strlen(token);
  35.             /* 前後の"'"を削除 */
  36.             if(token[0] == '\''){
  37.                 token++;
  38.                 token_len--;
  39.             }
  40.             if(token_len > 0 && token[strlen(token)-1] == '\''){
  41.                 token[strlen(token)-1] = '\0';
  42.                 token_len--;
  43.             }
  44.             /* 既知リストへの登録判断&登録 */
  45.             if( (token_len != 0) &&
  46.                 (exist(found_words, found_word_cnt, token) == 0 ) ){
  47.                 found_words[found_word_cnt++] = mystrdup(token);
  48.                 printf("%3d:%s\n", found_word_cnt, token);
  49.             }
  50.             token = strtok(NULL,DELIMITERS);
  51.         }
  52.     }
  53.    
  54.     printf("word count: %d\n", found_word_cnt);
  55.    
  56.     return 0;
  57. }
  58.  
  59. /* srcと同じ文字列をmallocで用意してそのポインタを返す */
  60. char *mystrdup(const char *src)
  61. {
  62.     char *p;
  63.    
  64.     if(src == NULL){
  65.         return NULL;
  66.     }
  67.     p = (char *)malloc(strlen(src) + 1);
  68.     if(p != NULL){
  69.         strcpy(p, src);
  70.     }
  71.     return p;
  72. }
  73. /* list内にwordがあれば1、なければ0を返す */
  74. int exist(char *list[], int list_num, const char *word){
  75.     int i;
  76.    
  77.     for(i=0;i<list_num;i++){
  78.         if(strcmp(list[i],word)==0) return 1;
  79.     }
  80.     return 0;
  81. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement