Actually,the following program is to split the string and display the output.I have done my program and it is giving the desired output.But,at the end it is giving segmentation fault.I tried with debugger also.But,I was unable to find the problem.can anyone help me?
Input File:
Vivek|Raj|20 Abi|Nila|20
Expected Output:
Vivek's last name Raj and age is 20. Abi's last name Nila and age is 20.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct person{
char firstname[30];
char lastname[30];
int age;
};
int main(int args, char *argv[])
{
struct person list[30];
int i,n;
char *ch,*ch1,*ch2,*ch3;
char buf[256];
FILE *fp;
fp = fopen(argv[1],"r");
if(fp == NULL){
printf("Cannot open file %s\n", argv[1]);
exit(0);
}
i=0;
fgets(buf,256,fp);
while(!feof(fp)){
ch = strchr(buf,'\n');
if(ch != NULL) *ch = '\0';
else break;
ch = strchr(buf,'|');
ch2 = strrchr(buf,'|');
if(ch != NULL)
{
*ch = '\0';ch1 = ++ch2;
}
else break;
ch++;
strcpy(ch3,ch);
ch2=strchr(ch3,'|');
*ch2='\0';
strcpy(list[i].firstname,buf);
strcpy(list[i].lastname,ch3);
list[i].age = atoi(ch1);
i++;
fgets(buf,256,fp);
}
n = i;
for (i = 0; i < n; i++)
printf("%s's last name %s and age.\n",list[i].firstname,list[i].lastname,list[i].age);
return 0;
}