Skip to content

Instantly share code, notes, and snippets.

@sudhanshuptl
Last active May 31, 2018 07:10
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/016c5374ca16f9331c28a9ddcf93eaa0 to your computer and use it in GitHub Desktop.
Save sudhanshuptl/016c5374ca16f9331c28a9ddcf93eaa0 to your computer and use it in GitHub Desktop.
Delimiter separated text file parsing in c
#include<stdio.h>
#include<string.h>
int main(){
FILE *fp; //file pointer
char line[30];
char *token;
//open file
fp = fopen("data.txt","r");
//check if any error in opening file
if(fp == NULL){
printf("Error in opening File ! ");
return -1;
}
while(fgets(line, sizeof line, fp) != NULL){
token =strtok(line,"|"); //string and delimiter is input
printf("\n______________________________________________\n");
while(token !=NULL){
printf("User1 : %s\n",token);
token = strtok(NULL,"|");
}
}
return 0;
}
#include<stdio.h>
#include<string.h>
#define DATA_SEGMENT 3
int main(){
FILE *fp; //file pointer
char line[30];
char *token;
int i;
//open file
fp = fopen("data.txt","r");
//check if any error in opening file
if(fp == NULL){
printf("Error in opening File ! ");
return -1;
}
while(fgets(line, sizeof line, fp) != NULL){
token =strtok(line,"|"); //string and delimiter is input
printf("\n______________________________________________\n");
//When we exactly know how much data will be
for(i =0;i<DATA_SEGMENT;i++){
if(i==0){
printf("FIRST NAME : %s\n",token);
token = strtok(NULL,"|");
}
else{ if(i==1){
printf("LAST NAME : %s\n",token);
token = strtok(NULL,"|");
}
else{
printf("Extention (integer) : %d\n",atoi(token));// converting to integer
}
}
}
}
return 0;
}
______________________________________________
User1 : sudhanshu
User1 : patel
User1 : 9452
______________________________________________
User1 : akash
User1 : masney
User1 : 4583
______________________________________________
User1 : Ashutosh
User1 : Dwivedi
User1 : 4587
______________________________________________
User1 : Atul
User1 : Abhishel
User1 : 1237
______________________________________________
User1 : Siddhart
User1 : Manu
User1 : 1238
______________________________________________
FIRST NAME : sudhanshu
LAST NAME : patel
Extention (integer) : 9452
______________________________________________
FIRST NAME : akash
LAST NAME : masney
Extention (integer) : 4583
______________________________________________
FIRST NAME : Ashutosh
LAST NAME : Dwivedi
Extention (integer) : 4587
______________________________________________
FIRST NAME : Atul
LAST NAME : Abhishel
Extention (integer) : 1237
______________________________________________
FIRST NAME : Siddhart
LAST NAME : Manu
Extention (integer) : 1238
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment