I have stored some website names with their corresponding ip addresses(random) in a text file named 'DNS'. For a particular website name I need to find its corresponding ip address. I tried the following C program. It shows the error
Segmentation fault (core dumped)
I am trying to check if the website is present in the file character by character, if found the read pointer is stopped at the last character of the website. After skipping a character, the rest of the characters are stored in an array called ip. But the same code works fine in windows. When I try in ubuntu it shows the above error. The code is
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main() {
// Write C code here
FILE* ptr = fopen("DNS.txt","r");
int found=0, i=0;
char website[20] = "google.com";
char ip[30];
char temp;
while ((temp=fgetc(ptr)) != EOF){
if (temp == website[i]){
i++;
if (i==strlen(website)){
found = 1;
break;
}
}
else
i=0;
}
if (found){
i=0;
temp = fgetc(ptr);
temp=fgetc(ptr);
while (temp != '\n'){
ip[i++]=temp;
temp=fgetc(ptr);
}
ip[i] = '\0';
printf("%s",ip);
}
else{
printf("Ip address not found");
}
return 0;
}
The DNS file looks like
google.com-1234.45.6
youtube.com-5738.292.22
github.com-2374.2342.2
The file is stored in the same location as the program.