在C中模拟WC命令的程序

  • 本文关键字:命令 程序 WC 模拟 c
  • 更新时间 :
  • 英文 :


我正在尝试用C编写一个程序,模拟C中的wc命令。

这就是我所拥有的,但它总是返回0。

有人能帮我澄清一下吗,因为我对C.不太熟悉

#include <stdio.h>
#include <string.h>
#include <unistd.h>

int main(int argc, char** argv)
{
int bytes = 0;
int words = 0;
int newLine = 0;
char buffer[1];
enum states { WHITESPACE, WORD };
int state = WHITESPACE;
 if ( argc !=2 )
 {
     printf( "Help: %s filename", argv[0]);
 }
 else{
     FILE *file = fopen( argv[1], "r");
   if(file == 0){
      printf("can not find :%sn",argv[1]);
   }
   else{
            char *thefile = argv[1];
      char last = ' '; 
      while (read(thefile,buffer,1) ==1 )
      {
         bytes++;
         if ( buffer[0]== ' ' || buffer[0] == 't'  )
         {
            state = WHITESPACE;
         }
         else if (buffer[0]=='n')
         {
            newLine++;
            state = WHITESPACE;
         }
         else 
         {
            if ( state == WHITESPACE )
            {
               words++;
            }
            state = WORD;
         }
         last = buffer[0];
      }        
      printf("%d %d %d %sn",newLine,words,bytes,thefile);        
   }
 } 
}

read(2)接受文件描述符作为第一个参数,而不是文件名

  while (read(thefile,buffer,1) ==1 )

应该是

  while (read(fileno(file),buffer,1) ==1 )

Btw:启用和读取编译器警告将指向的此类错误

编辑:

混合系统调用(read(2))和高级函数(fopen(3))通常不是一个好主意;使用fread(buffer, 1, 1, file)或使用open(2) 打开文件

最新更新