0

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);
Nocturno
  • 7,946
  • 5
  • 29
  • 39
glasspill
  • 1,259
  • 3
  • 21
  • 36
  • http://stackoverflow.com/questions/125828/capturing-stdout-from-a-system-command-optimally?lq=1 or http://stackoverflow.com/questions/43116/how-can-i-run-an-external-program-from-c-and-parse-its-output – Martin Beckett Dec 06 '12 at 03:39
  • Isn't there already a Unix or Linux program / tool / command to print the strings in a file? If so, you could just look at the source for it. – Thomas Matthews Dec 06 '12 at 04:03
  • ah, i see. it kept returning 0 except for a folder, because apparently all my files contained it. i thought it always returned 0 no matter what. silly me. thanks. – glasspill Dec 06 '12 at 13:30

2 Answers2

2

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

Chul-Woong Yang
  • 1,173
  • 8
  • 17
  • 2
    Note the exit code of the command issued via the call to `int status = system("some command")` is retrieved by applying the macro `int exitcode = WEXITSTATUS(status);`. – alk Dec 06 '12 at 09:59
1

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.)

chrisaycock
  • 32,202
  • 12
  • 79
  • 116