brijraj さんのプロフィールMaverick's Spaceフォトブログリストその他 ツール ヘルプ

ブログ


2008/02/21

Copy Lines from a file to an array of Character pointer or say char*array[]

 

SO I happened to be in position to write some C code, to copy the contents of a file line by line to an array of character pointers; for a .net guy it's nothing but array of strings, and each string would contain a line of this file, and we had to iterate line by line....seems easy so I came up with this code....

I initialised  the variables like

 

/* PS - it's a wrong code...I'll narrate the problem after U see the code...... */

char c[256]={0};
  FILE *file;

static char *recogArgv[6];

  file = fopen("MyArgs.txt","r");

if(file==NULL)
  {
      printf("No arguments supplied in the MyArgs..or the file doesn't exist");
      return 1;
  }

/* here goes my code to iterate line by line and put variables into the array of char*/
  else
  { int i = 0;     
      while(fgets(c,256,file)!=NULL)
      {              recogArgv[i] = c;        i = i + 1;               
      }
      fclose(file);}

so every time i ran this "Else" loop. it did get the new line in variable c but always, when i iterate i found that all the contents in the array of char* are same , obvious?

coz the c is nothing but a pointer, and it ought just copy the pointer address to the recogArgv, leading to the problem of same content in all the items of this array.

solution?    i did live search, Google search and nothing....people are talking about malloc, calloc, free....Guys  I am a .net guy and i want an API, I don't get registers...and hey I did found an API. and here's the right code...it uses strdup API to get me a duplicate address for the c which I would pass to my recogArgv and problem solved....

/* The perfect Code */

char c[256]={0};
  FILE *file;

static char *recogArgv[6];

  file = fopen("MyArgs.txt","r");

if(file==NULL)
  {
      printf("No arguments supplied in the MyArgs..or the file doesn't exist");
      return 1;
  }

/* here goes my code to iterate line by line and put variables into the array of char*/
  else
  { int i = 0;     
      while(fgets(c,256,file)!=NULL)
      {             

recogArgv[i] = strdup(c);  /*The use of strdup not only made my program pointer safe, but also helped me from getting into the malloc, calloc stuff */

        i = i + 1;               
      }
      fclose(file);}

Cheers!