0

Is there a way I can rewrite the following code which reproduce the functionality of the grep command in linux, in less lines of code? Or is there something I can make to save some memory or yo make the code even more efficient?

#include    <sys/types.h>
#include    <sys/stat.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <error.h>
#include    "ourhdr.h"
#define size 1024
int main(int argc, char **argv)
{
    char fis[100],car[10],buff[size];
    FILE *file;
if(argc!=3)
{
printf("Not all parameters were given <./a.out> <char> <numefisier>\n");
}
else
{
    file=fopen(argv[2],"r");
    if (file==NULL)
    {
    err_ret("Fisierul sursa nu exista %s", argv[2]);
    exit(0);
    }   
    strcpy(fis,argv[2]);
    strcpy(car,argv[1]);


    while((!feof(file)))
    {
        while(fgets(buff,size,file)!=NULL)
{
        if(strstr(buff,car))
            printf("%s \n",buff);
}


    }
    fclose(file);
}
return 0;
}
gameloverr2
  • 85
  • 2
  • 17
  • 5
    Packing the entire functionality of `grep` into less than 42 lines of code seems... *ambitious*. – Marco Bonelli May 04 '20 at 14:50
  • @MarcoBonelli Just this basic code, not all the functionality – gameloverr2 May 04 '20 at 15:05
  • 2
    There is no need to copy the arguments to `fis` or `car` — and you run the risk of overflow since you don't check that that the arguments are short enough to fit. [`while (!feof(file))` is always wrong!](https://stackoverflow.com/q/5431941/15168). In this case, it is simply pointless — the inner `while (fgets(…) != NULL)` loop is sufficient. Removing the outer loop saves 3 lines. Note that your printing is dubious; you add a stray blank and newline after the newline at the end of what `fgets()` read. Using `fputs(buff, stdout)` should work — unless `fgets()` didn't read the whole line. – Jonathan Leffler May 04 '20 at 15:11
  • 1
    Could you please fix the indentation? It's a mess. – Nate Eldredge May 04 '20 at 15:33

0 Answers0