I need to simulate the effect of the grep -f command between 2 files The code gets compiled with no errors, but when I run it instead of the output it displays Segmentation fault (core dumped) How can I that? Also if you can help with a better way to open f1 and f2 without using aux1 and aux2 to provide the name of the file that would be great. Thanks in advance.
//I know I have to check if the code has enough arguments and if not I should do something with stderr (that's I've been told to do in class but I don't know how)
#include <stdio.h>
#include <string.h>
int main(int argc, char *argv[])
{
FILE *file1;
FILE *file2;
char aux1[100]="",aux2[100]="";
strcpy(aux1,argv[1]);
strcpy(aux2,argv[2]);
file1 = fopen("aux1","r");
file2 = fopen("aux2","r");
char s1[100]="",s2[100]="";
char aux[100]="";
while(fscanf(file1,"%s",aux)!=EOF)
{
strcat(s1,aux);
strcat(s1," ");
}
s1[strlen(s1)-1]='\0';
while(fscanf(file2,"%s",aux)!=EOF)
{
strcat(s2,aux);
strcat(s2," ");
}
s2[strlen(s2)-1]='\0';
printf("%s\n",strstr(s2,s1));
return 0;
}
Here is one big mistake:
strcpy(aux1, argv[1]);
file1 = fopen("aux1", "r");
You aren't opening the file passed, and without checking whether it opened, you lurch right into a segfault by using a NULL
file pointer.
It should be
file1 = fopen(aux1, "r"); // removed " marks
if(file1 == NULL)
exit(1);
You also asked how to avoid using aux1
which can be done with
if(argc < 2)
exit(1);
fopen(argv[1], "r");