Read tab delimited file to Structure in C -
i have file tab delimited data. want read every line structure. have code read data char buffer. want load data structure.
this sample data.
empname1\t001\t35\tcity1
empname2\t002\t35\tcity2
my structure definition .
struct employee { char *empname; char *empid; int age; char *addr; };
my sample program read data char
array buffer
char buffer[buf_size]; /* character buffer */ input_fd = open (fsource, o_rdonly); if (input_fd == -1) { perror ("open"); return 2; } while((ret_in = read (input_fd, &buffer, buf_size)) > 0){ // process }
here want load content structure variable instead of character buffer. how can achieve that?
well, possible solution be
read complete line file using
fgets()
.tokenize input buffer based on required delimiter [
tab
in case] usingstrtok()
.allocate memory (
malloc()
/realloc()
) pointer variable of structure.copy tokenized inputs member variables.
note: 1. fgets()
reads , stores trailing \n
. 2. please check how use strtok()
. input string should mutable. 3. allocate memory pointers before using them. imo, use statically allocated array struct employee
member variables.
Comments
Post a Comment