Welcome to collectivesolver - Programming & Software Q&A. A website you can trust. All programs tested and works. Contact: aviboots(AT)netvision.net.il
Bonsai Trees

Liquid Web Managed Dedicated Server: RAID 1 SSD with 16GB of RAM minimum! 24/7 On-Site Heroic Support! Industry-Leading SLA!

BlueHost Web Hosting

Ecommerce Software - Best Ecommerce Platform Made for You - Free Trial

Ecommerce Software - Best Ecommerce Platform Made for You - Free Trial

getflywheel wordpress hosting


Liquid Web Cloud VPS Hosting

8,978 questions

12,389 answers

573 users

How to open and read text from a binary file in C

1 Answer

0 votes
#include <stdlib.h>
#include <stdio.h>

int main(void)
{
   int flag = EXIT_SUCCESS;

   char file_name[] = "d:\\data.bin";
   FILE *fp = fopen(file_name, "rb");
   
   if (fp == NULL) 
   {
     flag = EXIT_FAILURE;
     fprintf(stderr, "fopen() error\n");
   }
   else
   {
        fseek (fp , 0 , SEEK_END);
        size_t total = ftell (fp);
        rewind (fp);

        char *str = (char *) malloc (sizeof(char)*total);
        if (str == NULL) 
        { 
            fprintf(stderr, "malloc error\n");
            flag = EXIT_FAILURE;
        }
        else
        {
            size_t total_read = fread (str, 1, total, fp);
            if (total_read != total) 
            {
                flag = EXIT_FAILURE;
                fprintf(stderr, "fread() error\n");
            }
            else
                printf("str = %s\n", str);
                
            fclose(fp);
            free(str);
        }
   }

   return flag;
}
    
/*
run:
 
str = A text for binary file

*/

 




answered Aug 20, 2017 by avibootz
...