Skip to content

Instantly share code, notes, and snippets.

@sudhanshuptl
Created June 2, 2018 08:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sudhanshuptl/136c5860a9ec815135fe23c87cecbce1 to your computer and use it in GitHub Desktop.
Save sudhanshuptl/136c5860a9ec815135fe23c87cecbce1 to your computer and use it in GitHub Desktop.
Custom Function for delimiter seperated data parsing in c
sudhanshu|patel||1234
Chandan|kumar|54645
Ashutosh|Dwivedi|34654
#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;
}
______________________________
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