C :: Aufgabe #41 :: Lösung #1

3 Lösungen Lösungen öffentlich
#41

Schleifen - Reguläre Ausdrücke - Eingabe auf 'fred' prüfen

Anfänger - C von Gustl - 25.06.2013 um 15:24 Uhr
Schreiben Sie ein Programm, das jede Eingabezeile ausgibt, in der "fred" vorkommt. (Andere Eingabezeilen sollen nicht behandelt werden.) Das Muster soll auch Fred, Frederick, Alfred oder FrEd finden? (Egal ob die Buchstaben klein oder groß geschrieben werden.
#1
vote_ok
von devnull (8870 Punkte) - 28.06.2013 um 22:59 Uhr
Quellcode ausblenden C-Code
/********************************************
 * fred_3.c   search pattern in input stream
 *            using child process
 * 
 * OS     :   GNU/Linux
 * compile:   gcc -Wall -o fred fred_3.c
 * example:   echo Freddy|./fred -i fred    				
 *
 * devnull    28-06-2013                
 ********************************************/
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>

#define STR_LEN   62
#define BUF_LEN  254


/************
 * functions
 ************/
/* print usage on stderr */
void usage_exit( int exit_code )
{
  fprintf( stderr, "Usage: fred [-i] pattern\n" );
  exit(exit_code);
}

/* read input line from stdin */
int readln( char *line, int stripLF )
{
	int len;
	
	if (fgets(line, BUF_LEN, stdin) != NULL) {
		line[BUF_LEN]='\0';
		len=strlen(line);
		if (stripLF) {
			if (line[len-1] == '\n') {
				line[len-1] = '\0';
				len--;
			}
		}
		return len;
	}
	else
		return -1;
}

/*********
 *  main
 *********/
int main( int argc, char **argv )
{
    char linebuf[BUF_LEN+1];
    char pattern[STR_LEN+1];
    char command[STR_LEN+1];
    int opt, opt_icase=0;
    int slen;
    FILE* pp;

    /* check options [ih] */
    while ((opt = getopt( argc, argv, "ih" )) != -1) {
      switch(opt) {
          case 'i': opt_icase=1;         break;
          case 'h': usage_exit(EXIT_SUCCESS); break;
          default : usage_exit(EXIT_FAILURE);
      }
    }

	/* check args: search string/pattern */
    if (argc-optind != 1) 
		usage_exit(EXIT_FAILURE);
    strncpy( pattern,  argv[optind], STR_LEN );
    pattern[STR_LEN] = '\0';
	slen=strlen(pattern);
	if (slen == 0) {
		fprintf( stderr, "empty search string\n" );
		return 2;
	}

	/* build 'grep' command line */
	snprintf( command,STR_LEN,"/bin/grep -n%s '%s' -",opt_icase?"i":"",pattern );

	/* open pipe stream to child process */
	if ((pp=popen( command, "w" )) != NULL) {
		while (readln(linebuf,0) >= 0)
			fputs(linebuf,pp);
		pclose(pp);
	}
	else {
		fprintf( stderr, "cannot open pipe stream\n" );
		return 3;
	}
	return 0;
}

Kommentare:

Für diese Lösung gibt es noch keinen Kommentar

Bitte melden Sie sich an um eine Kommentar zu schreiben.
Kommentar schreiben