Thread: files, strings, comparation ...

  1. #1
    Registered User
    Join Date
    Oct 2002

    files, strings, comparation ...

    'grep string file > newfile'
    i need an idea how to do this in C.
    I know how to open, create files, compare strings .. etc ...etc ... but i'm newbie .. and making the whole thing out .. it's still hard for me

  2. #2
    Green Member Cshot's Avatar
    Join Date
    Jun 2002
    It seems like you already know most of the things needed to accomplish this. Here's one way:

    open new file for output
    open input file
    while not end of file
       get line
       compare search string with every string in line
       - if match, print line, increment count, etc...(whatever you want to do depending on the option set)
    end while
    print count to file, etc...
    close all files
    Try to code this out and we'll help you out if you run into problems.
    Try not.
    Do or do not.
    There is no try.

    - Master Yoda

  3. #3
    Registered User
    Join Date
    Nov 2002
    Instead of strcmp, try 'man strstr'.

  4. #4
    Registered User
    Join Date
    Oct 2002
    This seems to work ... thanks
    #include <string.h>
    #include <stdio.h>
    main ()
      FILE *cita;
      FILE *pise;
      char b[100];
      char string[] = "milan";
      cita = fopen ("/tmp/cita", "r");
      pise = fopen ("/tmp/pise", "w+");
      while ((fgetc (cita) != EOF))
          fgets (b, 100, cita);
          if ((strstr (b, string)) != 0)
                 fputs (b, pise);}
                 fclose (cita);
    		 fclose (pise);
                          return 0;
    Last edited by milan; 12-18-2002 at 02:20 AM.

  5. #5
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    >'grep string file > newfile'
    For simple comparisons, strstr is a good choice. If you want similar functionality to grep then you've got a lot of work ahead of you, grep is very thorough. If you'd like you can download the source code of a grep implementation from

    My best code is written with the delete key.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Help with reading strings and opening files PLEASE
    By green2black in forum C Programming
    Replies: 8
    Last Post: 11-17-2008, 05:46 PM
  2. Error opening files in a different dir
    By Ozzie in forum C++ Programming
    Replies: 3
    Last Post: 10-09-2008, 06:55 AM
  3. Working with muliple source files
    By Swarvy in forum C++ Programming
    Replies: 1
    Last Post: 10-02-2008, 08:36 AM
  4. Ofstream, Ifstream, Searching files for strings?
    By Zeusbwr in forum C++ Programming
    Replies: 10
    Last Post: 04-04-2005, 03:45 PM
  5. reinserting htm files into chm help files
    By verb in forum Windows Programming
    Replies: 0
    Last Post: 02-15-2002, 09:35 AM