Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,855 questions

51,776 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

Related questions

1 answer 170 views
1 answer 200 views
200 views asked Aug 19, 2017 by avibootz
1 answer 130 views
1 answer 136 views
1 answer 216 views
...