top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

how to read from file and store in multiple arrays in C?

+1 vote
367 views
how to read from file and store in multiple arrays in C?
posted Mar 30, 2014 by Prachi Agarwal

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

1 Answer

+1 vote

Since there is no limit on number of characters present in each line(this cannot be greater than 1000 assuming)

//Count the number of lines in file
int count_Lines()
{
  File *fp=fopen("example.txt","r");
  int n=0
   char arr[1000];
   while(fgets(arr,1000,fp)!=NULL){
    n++
 }
 flcose(fp)
 return n;
}

char **store(){
 char **arr.;
 int i;
 int n=count_Lines();
 fp=fopen("example.txt","r");
 arr=(char **)malloc(n*sizeof(int *)); //making array of pointers  
 i=0;
 do{
    arr[i++]=(char *)malloc(1000);   //making space for each line 
    }while(fgets(arr,1000,fp)!=NULL)
 fclose(fp);
 return arr;
}

If u want to have exact numbers characters in each array then u need to count number of characters in each line. In this case maintain a buffer of 1000 characters and store the characters in this buffer until u get a newline while counting number of characters.As soon as newline is encountered allocate sapce for it by passing the count to malloc and copy the buffer to it.

Keep iterating until eof is reached.

char **store(){
 char **arr;
 char buffer[1000].;
 int i,chars_inline;
 int n=count_Lines();
 fp=fopen("example.txt","r");
 arr=(char **)malloc(n*sizeof(int *)); //making array of pointers  
 i=0;
 chars_inline=0;
 while(!feof(fp)){
  buffer[chars_inline]=fgetc(fp);
  if(buffer[chars_inline]=='\n'){
     arr[i++]=(char *)malloc(chars_inline+1);
     strcpy(arr,buffer);
     chars_inline=0;
   }
  else 
    chars_inline++;
}
fclose(fp);
return arr;

Since it not clear from question what u want to read(numbers,characters, lines or blocks) so this much i could do. Hope this helps u.

answer Mar 31, 2014 by Prakash
Similar Questions
+2 votes

I tried something like this

uint32_t myint;   
char n[4]; 
size_t in;
 ...
 in = fread(n, 4, 1, fp); // value n is "\000\000\000\020"
 if (!in)
   return -2;
 myint = n; // get 4 bytes to integer 

but no luck..

...