how to get a string from a specific position in a file through c in ubuntu?

Viewed 47

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.

1 Answers

Given your file format, it would be easier to just slurp in the entire line with fgets and then use something like strtok or sscanf to split it into the name and address fields, then compare the name to the desired name. Bit more straightforward and you're making the standard library do the hard work (which is why it's there).

Incomplete example with no error checking:

#define LINE_LENGTH 80 // or whatever your maximum input line length
                       // happens to be
...
char line[LINE_LENGTH+1] = {0}; 

while ( fgets( line, sizeof line, ptr ) )
{
  char ip[LINE_LENGTH+1] = {0};
  char name[LINE_LENGTH+1] = {0};

  if ( sscanf( line, "%[^-]-%[^\n]", name, ip ) == 2 )
  {
    if ( strcmp( name, website ) == 0 )
    {
      printf( "%s", ip );
      break;
    }
  }
}

You'll want to add some error checking to handle input lines that are longer than your buffer is sized to hold and similar robustification, but this should steer you in the right direction.

Related