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

  1. read complete line file using fgets().

  2. tokenize input buffer based on required delimiter [tab in case] using strtok().

  3. allocate memory (malloc()/ realloc()) pointer variable of structure.

  4. 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

Popular posts from this blog

java - Plugin org.apache.maven.plugins:maven-install-plugin:2.4 or one of its dependencies could not be resolved -

Round ImageView Android -

How can I utilize Yahoo Weather API in android -