Created
June 2, 2018 08:06
-
-
Save sudhanshuptl/136c5860a9ec815135fe23c87cecbce1 to your computer and use it in GitHub Desktop.
Custom Function for delimiter seperated data parsing in c
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
sudhanshu|patel||1234 | |
Chandan|kumar|54645 | |
Ashutosh|Dwivedi|34654 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include<stdio.h> | |
#include<string.h> | |
#include<stdlib.h> | |
/*Global Variabls*/ | |
char *GlobalPointer=NULL; | |
/* Prototypes */ | |
char *ParseLine(char *arr, char *delimiter); | |
int main(){ | |
FILE *fp; | |
char line[50]; | |
char *token; | |
//open file | |
fp = fopen("data.txt","r"); | |
if(fp == NULL){ | |
printf(" Error in opening File !\n"); | |
exit(1); | |
} | |
//read line by line and process | |
while (fgets(line,sizeof line,fp) != NULL) { | |
//printf("%s\n",line ); | |
printf("______________________________\n" ); | |
token = ParseLine(line,"|"); | |
while (token !=NULL) { | |
printf("data : %s\n",token ); | |
token = ParseLine(NULL,"|"); | |
} | |
} | |
fclose(fp); | |
return 0; | |
} | |
char *ParseLine(char *arr, char *delimiter){ | |
int position; | |
char *blockString; | |
char *ptr; | |
if(arr != NULL){ | |
GlobalPointer = arr; | |
} | |
else{ | |
arr = GlobalPointer; | |
} | |
if(GlobalPointer == NULL) | |
return NULL; | |
position = strcspn(arr, delimiter); | |
//printf("postion :%d\n",position ); //debug | |
if(position <= 0){ | |
if(*GlobalPointer == '\n' || *GlobalPointer == '\0'){ | |
return NULL; | |
} | |
else{ | |
GlobalPointer++; | |
return "\0"; | |
} | |
} | |
//allocate memory | |
blockString = (char *) calloc(position+2,sizeof(char)); | |
ptr = blockString; | |
while(position--){ | |
*ptr++ = *arr++; | |
} | |
arr++; | |
GlobalPointer = arr; | |
return blockString; | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
______________________________ | |
data : sudhanshu | |
data : patel | |
data : | |
data : 1234 | |
______________________________ | |
data : Chandan | |
data : kumar | |
data : 54645 | |
data : | |
______________________________ | |
data : Ashutosh | |
data : Dwivedi | |
data : 34654 | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment