Friday 11 March 2016

C fgets bait

I wrote a little program which count the char in a text given, and put it into buffer to return.
It just open the file then use a fgetc() loop  to count char number, then invoke fgets() to put the content into buffer with a size of char number.


char *read_dna_file(char* filename)
{
 unsigned size = 0, line = 0;
 char* buffer = NULL;
 FILE *fstream = fopen(filename, "r");

 if(fstream == NULL)
  return NULL;
 else
 {
  while(fgetc(fstream) != EOF)
   size++;
 }
  printf("%d\n",size);
  buffer = (char*)malloc(size + 1);
  char* code = fgets(buffer, size, fstream);
  fclose(fstream);
 return code;
}

int main()
{
 char* temp = read_dna_file("dna-moutarde.txt");
 printf("%s\n",temp);
}
Segmentation Fault

At the beginning, I had always the same error, segmentation fault, I have no idea where is the problem. With the help of my friend, he point out that the fgetc() will store the address the last time used, when fgets() is invoked, fgets() will continue to read the file from the last position saved.
So the solution is:
Close the file and reopen it. fgets() will read from the beginning of file, or use fseek() to shift the pointer to the beginning. And it works.



char *read_dna_file(char* filename)
{
 unsigned size = 0, line = 0;
 char* buffer = NULL;
 FILE *fstream = fopen(filename, "r");

 if(fstream == NULL)
  return NULL;
 else
 {
  while(fgetc(fstream) != EOF)
   size++;
 }
  printf("%d\n",size);
  fseek(fstream, 0, SEEK_SET); 
  //            OR
 //  fclose(fstream);
//         fstream = fopen(filename, "r");
  buffer = (char*)malloc(size + 1);
  char* code = fgets(buffer, size, fstream);
  fclose(fstream);
 return code;
}

int main()
{

 char* temp = read_dna_file("dna-moutarde.txt");
 printf("%s\n",temp);
}

No comments:

Post a Comment