Zurück zur SPiC Übersicht
sgrep.c
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#ifndef MAX_LINE_SIZE
#define MAX_LINE_SIZE sysconf(_SC_LINE_MAX)
#endif
static void die(const char *msg) {
perror(msg);
exit(EXIT_FAILURE);
}
static void suche_in_datei(const char *suchtext, const char *dateiname) {
FILE *fp = fopen(dateiname, "r");
if (!fp) {
die(dateiname);
}
char buf[MAX_LINE_SIZE];
int line = 0;
while (fgets(buf, MAX_LINE_SIZE, fp) != NULL) {
line++;
if (buf[strlen(buf) - 1] == '\n') {
buf[strlen(buf) - 1] = '\0';
}
if (strstr(buf, suchtext) != NULL) {
printf("%s:%d\t%s\n", dateiname, line, buf);
}
}
if (ferror(fp)) {
die(dateiname);
}
fclose(fp);
}
int main(int argc, char *argv[]) {
if (argc < 3) {
fprintf(stderr, "Syntax: %s <suchtext> <dateien...>\n", argv[0]);
exit(EXIT_FAILURE);
}
const char *suchtext = argv[1];
for (int i = 2; i < argc; i++) {
suche_in_datei(suchtext, argv[i]);
}
}