Is it possible to get the size of a string for the function fread()

77 Views Asked by At

I need to get the size of a string to pass to the function read() below is the code that I have tried to implement finding the size of the string using the function size of but it doesn't work

 #include <stdlib.h>

int main()
{
    int num;
    char *string;
    FILE *fptr;

   // use appropriate location if you are using MacOS or Linux
   fptr = fopen("program4.txt","r");

   if(fptr == NULL)
   {
      printf("Error!");
      exit(1);
   }
    
    
    fread(string, /*issuse */sizeof(string), 1, fptr);
       printf("%s\n", string);
    
    fclose(fptr);

   return 0;
}
1

There are 1 best solutions below

0
Lundin On
  • Correct use would rather be fread(string, 1, n, fptr); where 1 is the size in bytes of a char (guaranteed to be 1) and n is the allocated size of your character array. However, fread reads raw binary and doesn't know about things such as null termination. It reads exactly 1 * n bytes. So it isn't suitable unless the strings in the text file are of fixed size and zero-padded... which is probably not the case here(?).
  • fgets is likely more suitable since it stops reading upon end of line '\n', so in case you have a text file with strings of variable length, each written on a line of its own, then fgets is the way to go.
  • No matter which function you use, always check the result for errors. fread returns 0 upon unsuccessful read, fgets returns a null pointer.
  • You never allocated any memory for string so you can't store anything in it. sizeof can't be used on pointers, only on arrays allocated with fixed size.
  • It may be reasonable to allocate the string to some maximum allowed size in advance. For example 80 characters + 1 null terminator, or whatever makes sense for your file format.