1

 #include <stdio.h>

#include <stdlib.h>


void string_split(char * string, char sep, char *** r_array_string, int * r_size) {

char * string2 = string;

int i, k, len, size;

char ** array_string;

// Number of substrings

size = 1, len = strlen(string2);

for(i = 0; i < len; i++) {

if(string2[i] == sep) {

size++;

}

}

array_string = malloc(size * sizeof(char*));

i=0, k=0;

array_string[k++] = string2; // Save the first substring pointer

// Split 'string' into substrings with \0 character

while(k < size) {

if(string2[i++] == sep) {

string2[i-1] = '\0'; // Set end of substring

array_string[k++] = (string2+i); // Save the next substring pointer

}

}

*r_array_string = array_string;

*r_size = size;

return;

}


int checkUserID(char *line){

    char ** array_string;

int i, size;

string_split(line, ',', &array_string, &size);

//printf("Number of substrings: %d \n", size);

//array_string[i]

for(i = 0; i < size; i++) {

if (i == 0){

if (strcmp(array_string[i], "1001508") == 0){

printf("UserID : %s \n", array_string[0]);

printf("ProductID : %s \n", array_string[1]);

printf("Gender : %s \n", array_string[2]);

printf("Age : %s \n", array_string[3]);

printf("Purchase : %s  ", array_string[4]);

}

}

}

return 0;

}


int main(){

FILE *fp = fopen("data.txt.txt", "r");

    size_t len = 255;

    // need malloc memory for line, if not, segmentation fault error will occurred.

    char *line = malloc(sizeof(char) * len);

    // check if file exist (and you can open it) or not

    if (fp == NULL) {

        printf("can open file data.txt.txt!");

        return;

    }

    while(fgets(line, len, fp) != NULL) {

    //printf("%s", line);

    checkUserID(line);

//printf("%s", line);

    }

    free(line);


return 0;

}

Komentar