I am getting a segmentation fault when I want to run this program. It is supposed to by a self-written grep function but case-insensitive. The same code for case-sensitive works just fine so it might have something to do with tolower()?. Please help. Used VS code in Ubuntu on a Windows PC.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
int main (int argc, char *argv[]) {
if (argc > 3) {
printf("Too many arguments. Only use 2: your search string and the file name.");
return -1;
}
//FILE * fp;
FILE * fp = fopen(argv[2], "r");
if(fp == NULL) {
perror("Unable to open file!");
return -1;
}
char * buffer = NULL;
size_t bufsize = 0;
char * lowerBuffer = malloc(sizeof(strlen(buffer)));
for (int i = 0; buffer[i] != '\0'; i++) {
lowerBuffer[i] = tolower(buffer[i]);
}
printf("tolower: %s", lowerBuffer);
while (getline(&buffer, &bufsize, fp) != -1) {
if (strstr(buffer, argv[1]))
{
printf("%s", buffer);
}
//printf("%zd", strlen(buffer));
}
fclose(fp);
free(buffer);
//getline();
return 0;
}
Compiled with gcc mygrepin.c, run with ./a.out test test.txt.
This is what my test.txt looks like:
hallo das ist ein Test.
test
test
test
test
test
I am expecting this output for this command ./a.out test test.txt:
hallo das ist ein Test.
test
test
test
test
test