glasspill
glasspill

Reputation: 1300

Determine if a file contains a certain string

I am looking for a way to determine if a certain file contains a certain string. It can be a system call or a C function, it doesn't matter.

I tried with grep, but it doesnt return anything

  //name is the directory entry name
   char grepcmd[150];
      strcpy(grepcmd,"grep -c hello ");
      strcat(grepcmd, name);
      int status = system(grepcmd);

Upvotes: 0

Views: 156

Answers (2)

Chul-Woong Yang
Chul-Woong Yang

Reputation: 1243

You are doing well. status should be zero if your given file with name name contains hello string. Otherwise it should be nonzero value.

Upvotes: 2

chrisaycock
chrisaycock

Reputation: 37938

If you're up for system calls, then just mmap() the file and call something like strnstr(). (You won't be able to call the real strnstr() since it will stop at any \0 in your file, so you'll have to write your own.)

Upvotes: 1

Related Questions