简体   繁体   中英

grep: search multiple files

I wrote a program ( grep ) that does a search in several files

I would like you to help me get rid of the following warnings I receive when I run with make在此处输入图像描述 . What should I change?

code:

#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <fcntl.h>
#include <string.h>
#include <sys/stat.h>

void grep_function(char *path, char *pattern)
{
    struct stat statbuf;
    if(lstat(path, &statbuf) == 0) 
    {
        if(S_ISDIR(statbuf.st_mode))
        {
            char buf[255];
            snprintf(buf,255,"grep: %s: Is a directory\n",path);
            write(2,buf,strlen(buf));
            return;
        }
    }
    int fd = open(path,O_RDONLY);
    if(fd<0)
        {     
            char buf[255];
            snprintf(buf,255,"File %s does not exist or is invalid\n",path);
            write(2,buf,strlen(buf));
            return;
        }
    int size=lseek(fd,0,SEEK_END);
    lseek(fd,0,SEEK_SET);
    char c;
    int k=0;
    for(int i=0; i<size; i++)
        {
            read(fd,&c,1);
            k++;
            if(c=='\n')
                {
                    char *sir = malloc((k+1)*sizeof(char));
                    lseek(fd,-k,SEEK_CUR);
                    read(fd,sir,k-1);
                    sir[k-1]='\0';
                    char *ret;
                    ret = strstr(sir, pattern);
                    if(ret!=NULL)
                        printf("%s:%s\n",path,sir);
                    free(sir);
                    lseek(fd,i+1,SEEK_SET);
                    k=0;
                }

        }
    if(k!=0)
    {
        char *sir = malloc((k+1)*sizeof(char));
        lseek(fd,-k,SEEK_CUR);
        read(fd,sir,k);
        sir[k]='\0';
        char *ret;
        ret = strstr(sir, pattern);
            if(ret!=NULL)
                printf("%s:%s\n",path,sir);
        free(sir);
    }
    close(fd);
}

int main(int argc, char **argv )
{
    if(argc<3)
        {
            printf("Invalid number of parameters!\n");
            return 1;
        }
    for(int i=2; i<argc; i++)
        {
            grep_function(argv[i],argv[1]);
        }
    return 0;
}

write() returns a value, which is the number of characters written. You are being warned that you are ignoring potentially valuable information. You can cast it to void to silence it if you really don't care ( (void)write(...) ). Similarly with read() .

If you are unsure of the reasons why write might return less than the specified number of bytes, check the docs.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM