【问题标题】:Implementing grep in c using system calls使用系统调用在 c 中实现 grep
【发布时间】:2013-01-20 13:31:02
【问题描述】:
#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>
#include <sys/types.h> 
#include <sys/stat.h>
#include <unistd.h>
#include<string.h>
#include <fcntl.h>

void match_pattern(char *argv[])
{
    int fd,r,j=0;
    char temp,line[100];
    if((fd=open(argv[2],O_RDONLY)) != -1)
    {
        while((r=read(fd,&temp,sizeof(char)))!= 0)
        {
            if(temp!='\n')
            {
                line[j]=temp;
                j++;
            }
            else
            {
                if(strstr(line,argv[1])!=NULL)
                    printf("%s\n",line);
                memset(line,0,sizeof(line));
                j=0;
            }

        }
    }   
}

main(int argc,char *argv[])
{
    struct stat stt;
    if(argc==3)
    {
        if(stat(argv[2],&stt)==0)
            match_pattern(argv);
        else 
        {
            perror("stat()");
            exit(1);
        }
    }
}

文件内容:

arunds ghh
sdf
hi
hello dude
am arun

我的输出:

./mygrep arun file
arunds ghh
am arun

得到正确的输出

文件内容:

arun arundfdf arun
arunds ghh
sdf

我的输出:

./mygrep arun file
arun arundfdf arun �5
arunds ghh

我不知道为什么会打印一些不需要的字符。

【问题讨论】:

  • 如果对性能感兴趣,请读取缓冲区,然后逐个字符地从缓冲区中获取。 read() 的开销确实很大。所以基本上,重新实现 stdio getchar。

标签: c grep system-calls


【解决方案1】:

你永远不会 NULL 终止你的 line 缓冲区,所以它会在结束后溢出。在声明了line 变量之后也运行memset 调用。

【讨论】:

  • 非常感谢!!我在 if(strstr(line,argv[1])!=NULL) 上面添加了 line[j]='\0'
【解决方案2】:

您需要对line 进行空终止,但为什么一次读取一个字符?您可以使用fgets() 读取整行,这将为您终止缓冲区:

while (fgets(line, sizeof(line), file)) {
   if (strstr(line, argv[1])) {
    ...
   }
}

这也将确保您不会溢出您分配的 100 字节缓冲区。

【讨论】:

  • @BartFriederichs 是的,这是另一个问题。
  • 其实我只需要使用系统调用
  • @user1958241 这些不是系统调用,它们是标准 C 库中的函数,甚至 read() 也是一个函数 :) 无论如何,至少要确保你读取的字节数不超过 99 个跨度>
  • 据我所知,fgets() 是一个函数,它在标准 C 中,但 read() 是一个 unix 系统调用。
  • @user1958241 read() 只是一个调用内核并传递读取的系统调用号和参数的包装器,我确信您的分配不需要使用真正的系统调用。如果您想了解区别,请参阅此内容。 stackoverflow.com/questions/2668747/…
猜你喜欢
  • 2012-09-28
  • 2017-02-14
  • 2012-09-19
  • 2016-05-25
  • 2016-01-18
  • 2012-08-22
  • 2014-10-15
  • 2015-05-24
  • 2018-04-04
相关资源
最近更新 更多