#include <stdio.h>
    #include <stdlib.h>
    
    typedef struct filedata
    {
            char data[100];
    }data_t;
    
    data_t * fname=NULL;
    
    //IS AN ARRAY OF the structure filedata REQUIRED HERE
    
    void quit()
    {
          printf("\nPress enter to exit");
          fflush(stdin);
              getchar(); 
    }    
                                         
                    
    int main()
    {
    char ch;   
        fname=(data_t *)malloc(sizeof(data_t));
    
        FILE *fptr=NULL;
        atexit(quit);
        printf("Please enter the file name to read : ");
        fflush(stdin);
        scanf("%s",fname->data);    
        fptr=fopen(fname->data,"rb");
    
        if(fptr == NULL)
        {
                perror("Could not open the file ");
                return;
        }
        printf("\n+++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n");
        printf("Contents of the file %s are : ",fname->data);
    
       [B] while(fread(&fname, sizeof(data_t), 1,fptr) == 1)
        {
          // what do I put here? 
        }[/B]
    
        fclose(fptr);       
        return 0;
    }

I want to read any binary file contaning some text or numbers in it on my computer and display it on the stdout.

How do I do it?

Shall I declare an array of the structure file data like `data_t data[100]`?
What should I put in the while loop above to display the contents?

An example : of course if I know the attributes inside the some stucture like name,age etc then I can do something like

while ( fread ( &e, sizeof ( e ), 1, fp ) == 1 )
printf ( "\n%s %d %f", e.name, e.age, e.bs ) ;

But how do I read any text contents of any binary file and display it to stdout?

Can somebody look into it please... may be I could get an idea or something?

Recommended Answers

All 11 Replies

You don't have to loop through every byte read.
You can do

fread(&(fname->data), sizeof(char), text_length, fptr);

if you know the amount of characters in the file.
Otherwise you can do

int i = 0;
while(!feof(fptr))
{
fread((&(fname->data)) + i, sizeof(char), 1, fptr);
i++;
}

Remember that you must append a null character to the string.
(you can memset the array before using it so it contains only nulls)

Hope this helps.

PS. I edited out a lot of errors haha :)

Really, why would you want to? You know that some of the binary characters have no ascii representation, hence can't be displayed. It would be better to display each binary value in hex, thus displaying each and everyone of them.

Alternatively, use isprint to determine if there's a printable representation of the character, and show the numeric value if there is not.

I got this guys from another forum and the answer from a person named jim was below :

In order to read a binary file you must know how the file was written. You must know how the variables were written, their size, in bytes. Their type, double, float, int, char, user defined type, etc. The order these variables were written to the file. And last the number of bytes required to hold each variable.

So it is usually not possible to take "any" binary file and read the contents. You may read a select binary file that you know the exact layout, but not a binary file that you do not know the layout.

Jim

So thats true hmmm.. its not possible

Try compiling this program

testp.c

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

int main(int argc, char**argv)
{
  char ch;
  FILE *fd = NULL;
  
  if ( argc != 2 )
  {
	fputs("usage error - a.out <Filename>\n", stderr);
	exit(EXIT_FAILURE);
  }
  
  if (!(fd = fopen(argv[1], "r")))
  {
	fprintf(stdout, "Could not open %s\n", argv[1]);
	exit(EXIT_FAILURE);
  }
  
  while (fread(&ch, sizeof(char), 1, fd))
  {
	fprintf(stdout, "%p ", (void*)ch);
  }
  
  fclose(fd);
  return 0;
}

Now pass a file name as a command line argument..It should display the binary(hex values) contents of the file.

Gerard , compilation gives error :

testp.c: In function `main':
testp.c:23: warning: cast to pointer from integer of different size

It's a warning and it's quite irrelevant. Every pointer is just a number. The compiler warns you that you might make a mistake (e.g. write 32-bit integers into an array of bytes and make a "buffer overflow").

It's a warning and it's quite irrelevant.

It's a warning, but hardly irrelevant. The warning tells me that either the author made a mistake and meant &ch, or was hoping %p would print a hexadecimal value and was trying to be clever. Either way, the code is wrong. The fix for the latter is to recognize that fprintf already supports hexadecimal output without subverting the type system:

fprintf(stdout, "%3x", ch);
#include<stdio.h>
#include<conio.h>
void main()
{
    struct student
    {
        char name[30];
        char adr[50];
    };
    struct student s;
    char next='y';
    FILE *fp;
    clrscr();
    fp=fopen("st.txt","w");
    while(next=='Y' || next=='y')
    {
      printf("\nEnter the name and address of the student:");
      gets(s.name);
      gets(s.adr);
      fwrite(&s, sizeof(s),1,fp);
      printf("\nDo you wnat to continue y/n");
      next=getche();
    }

    fclose(fp);
    fp=fopen("st.txt","r");
    printf("\nName \t\t address:");
    while(fread(&s,sizeof(s),1,fp)==1)
    {
        printf("\n%s\t\t%s\n",s.name,s.adr);
    }
    fclose(fp);
    getch();
}

please help me that how to display data from binary data file in c.

Well, what seems to be the problem? I ran your program after taking out the conio.h stuff since I see no need for it here plus I'm not good at debugging it. I prefer a plain old console program here. As the user, I want to be able to enter input and erase it if I don't like what I inputted it and not have the program proceed until I hit the Enter key. There are some programs where capturing each keystroke might be helpful, but I find it detrimental here. That's just my personal opinion. YMMV.

Here's your program, slightly revised to take away the conio.h stuff and instead use the stdio.h functions. I also put your struct above main rather than inside main, and I changed main to return an integer rather than being a void function. Finally, note the buffer[100] array that I added in order to get rid of the conio.h stuff and still read through to the end of the line. Note that I used getchar rather than getche because it's standard plus some of the reasons listed above. I also made it clearer to the user that it was expected that a name would be entered then ENTER, then an address, then ENTER.

It's still your program. It seems to work, so again, what is the question? I personally don't see the point in making this a binary file rather than a text file. You need to run a compter program to see data that makes sense. I see no need for that.

#include<stdio.h>

struct student
{
    char name[30];
    char adr[50];
};

int main()
{
    char buffer[100];  // just a buffer to eat up any extra characters from a line from stdin
    struct student s;
    char next='y';
    FILE *fp;
    fp=fopen("st.txt","w");
    while(next=='Y' || next=='y')
    {
      printf("\nEnter the name the student:");
      gets(s.name);
      printf("\nEnter the address of the student:");
      gets(s.adr);
      fwrite(&s, sizeof(s),1,fp);
      printf("\nDo you wnat to continue y/n");
      next=getchar();
      gets(buffer); // grab any remaining characters from the line, especially the newline.  Do nothing with it.
    }

    fclose(fp);
    fp=fopen("st.txt","r");
    printf("\nName \t\t address:");
    while(fread(&s,sizeof(s),1,fp)==1)
    {
        printf("\n%s\t\t%s\n",s.name,s.adr);
    }
    fclose(fp);
    return 0;
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.