vatsal511 vatsal511 - 1 month ago 15
C Question

Pointer issue not solved

In the below code, the file test.txt has the following data :

192.168.1.1-90
192.168.2.2-80


The output of this is not as expected. I expect the output to be

192.168.1.1
90
192.168.2.2
80


The current output is

192.168.2.2
80
192.168.2.2
80


I know that the pointer of str is pointing to the same address in the second iteration as well.

Im just not able to the problem.
Any help would be appreciated.

#include <string.h>
#include <stdio.h>
#include <stdlib.h>
int main() {
FILE * fp;
char * result[10][4];
int i = 0;
const char s[2] = "-";
char temp[50];
char * value, str[128], * string, t[20], x[29] = "192.168.2.2";
fp = fopen("test.txt", "r");
if (fp == NULL)
printf("File doesn't exist\n");
else {
while (!feof(fp)) {

if (fgets(str, sizeof(str), fp)) {

/* get the first value */
value = strtok(str, s);

result[i][0] = value;
printf("IP : %s\n", result[i][0]); //to be removed after testing


/* get second value */
value = strtok(NULL, s);

result[i][1] = value;
printf("PORT : %s\n", result[i][1]); //to be removed after testing
i++;
}
}
for (int k = 0; k < 2; k++) {
for (int j = 0; j < 2; j++) {
printf("\n%s\n", result[k][j]);
}
}

}
return (0);
}

Answer

I propose like this:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

enum { IP = 0, PORT = 1};

int main(void){
    FILE *fp;
    char result[2][2][16];//2 lines, 2 kinds, 16:XXX.XXX.XXX.XXX+NUL
    const char *s = "-";//delimiter
    char *value, line[128];
    int i=0;

    fp = fopen("test.txt", "r");
    if (fp == NULL) {
        printf("File doesn't exist\n");
        exit(EXIT_FAILURE);
    }
    while(i < 2 && fgets(line, sizeof(line), fp)){
        value = strtok(line, s);
        strcpy(result[i][IP], value);
        printf("IP : %s\n",result[i][IP]);

        value = strtok(NULL, s);
        strcpy(result[i][PORT], value);
        printf("PORT : %s\n",result[i][PORT]);
        i++;
    }
    puts("");
    for (int k=0;k<2;k++){
        for (int j=0;j<2;j++){
            printf("%s\n",result[k][j]);
        }
    }
    fclose(fp);

    return 0;
}