Solved

How to read,process & write a binary file?

Posted on 1998-09-17
12
9,566 Views
Last Modified: 2010-05-18
Hello

I have an image file (binary format). I want to write a C program that does the following:
1) I need to read this image in binary.
2) Then I want to make some processings(do    some calculations to tha input image).
3)  Finally, I want to rewrite the results after the         changes in in binary format.

Is that feasible in C ? and How can I do it?
Thanks

0
Comment
Question by:oualide
  • 4
  • 3
  • 2
  • +2
12 Comments
 
LVL 7

Expert Comment

by:faster
ID: 1252843
Of course.  Just use C runtime library functions: fopen, fclose, fread, fwrite.  Only these four functions are enough for your file processing and they are supported on all platforms where C is implemented.
0
 

Author Comment

by:oualide
ID: 1252844
Ok but When I read a binary file that contains some data, how can I process the data I read. For example,
I read an element of the data file
I want to add 100 to it.
then write it in binary to the output file.
Can you read a binary element from a file - say extract a variable ?if yes can you print it on the scren ?
How can you add 100 to a binary element ?
Thanks
0
 
LVL 7

Expert Comment

by:faster
ID: 1252845
when you read, you just read the binary content into a buffer, how to extract variable and do the processing is all your business.  After the processing is done, you need to put it to a buffer and then write it back.
0
 
LVL 84

Expert Comment

by:ozo
ID: 1252846
How is the "element" represented in your binary file?
0
 
LVL 10

Expert Comment

by:rbr
ID: 1252847
e.g.

FILE *pfin,*pfout;
int v_int;
double v_double;
char v_char[200];

pfin=fopen("infile","rb");
pout=fopen("outfile;"wb"); /* Creates a new file */

fread (&v_int,sizeof(v_int),1,pfin); /* Read in an integer */
fread (&v_double,sizeof(v_double),1,pfin); /* Read in an double */
fread (v_char,sizeof(char),200,pfin); /* Read in 200 chars */

v_int+=100;
fwrite (&v_int,sizeof(v_int),1,pfout); /* Write back altered data */
fwrite (&v_double,sizeof(v_double),1,pfout); /* Write back */
fwrite (v_char,sizeof(char),200,pfout); /* Write back */
fclose (pfin);
fclose (pfout);

You can read in also a structure

struct any_struct {
int v1;
double v2;
char v3[100];
}

struct any_struct data;

fread (&data, sizeof(data),1,pfin);

If this example will help you pls reject faster's answer and give the points to me.

0
 
LVL 84

Expert Comment

by:ozo
ID: 1252848
but be aware that the this may not be compatible between machines with different numeric representations,
or compilers using different structure alignment and padding
0
How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

 

Author Comment

by:oualide
ID: 1252849
To ozo:
I dont know. All I know it is a binary file.

To rbr,

I will give you the points if you can help me with this. I think you missunderstood me. When I said:
2) Then I want to make some processings(do some calculations to tha input image).  I mean how can you read binary and then add/multiply an integer to it. Thanks
0
 
LVL 2

Expert Comment

by:duneram
ID: 1252850
oualide:

The key to reading binary and iterpretting appropriately is something like this

If you declare:

long myvar = 0;

/* some where in your code, you open the file and now are going to read it */
FILE *fp;
fp = fopen("mybinfile.bin", "rb");
fread (&myvar,sizeof(myvar),1, fp);

At this point, the data was read into your 'variable' as 4 bytes of binary data.  The 4 bytes of data are interpreted as a 'long'.  If you 'add 100' to your variable you will end up with a number that is 100 more than the original number.  It has a binary representation.

If you then do a fwrite of the 'myvar' it will write the new value to the file.  fwrite in this case would write the myvar to the file as 4 bytes of binary information (since it's a long).

The compiler will take care of handling the binary to long conversion for you.

By the way avoid declaring things with 'int'  Especially if you are dealing with binary files.  The reason is on different platforms the size of an 'int' will vary.   For example if you declare

int x;  /* on 16 bits its 2 bytes long, on 32 bits its 4 bytes long */

if you wrote that to a file in a 16 bit program, you would be writing 2 bytes of information.  In a 32 bit program you would be writing 4 bytes of information.  say you wrote it using a 16 bit program, then later tried to read it using a 32 bit program, if you did that you would get the wrong answer when you went to read it back.  

If you (in the example) had declared

short x;  

This would have worked in both 16 bits and 32 bits as only 2 bytes would need to be read /written.

LEt me know if you wnat more info.



0
 

Author Comment

by:oualide
ID: 1252851

To rbr,
========
 I will give you the points if you can help me with this. I think you missunderstood me. I know the processing is up to me. When I said: 2) Then I want to make some processings(do some calculations to tha input image). I mean how can you read in binary and then add/multiply an integer to it or whatever calculations. Don't you need to convert and then do the calculations.

Thanks





0
 
LVL 2

Expert Comment

by:duneram
ID: 1252852
This is very simple and it runs


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


int main (int argc, char *argv[])
{
      /* demonstrates read/write of a binary file */
      FILE *fp;
      long TestValue;
      char Fname[]="Test";

    unlink(Fname);
      TestValue = 100;
      fp = fopen(Fname, "wb");
      if (fp)
      {
            fwrite(&TestValue, sizeof(long), 1, fp);
            fclose(fp);

            printf("File 'Test' Created  Wrote 100 to file\n");

            fp = fopen(Fname, "rb");
            if (fp)
            {
                  TestValue = 99; /* set to another value to prove test */
                  fread(&TestValue, sizeof(long), 1, fp);
                  printf("Just opened 'Test' and read %ld from the file\n", TestValue);

                  fclose(fp);
                  TestValue = TestValue + 23;
                  printf("New value to write back to file is %ld\n", TestValue);
                  fp = fopen(Fname, "wb");
                  if (fp)
                  {
                        fwrite(&TestValue, sizeof(long),1,fp);
                        fclose(fp);
                        TestValue = 98;  /* Set another value to prove it */
                        fp = fopen(Fname, "rb");
                        fread(&TestValue, sizeof(long), 1, fp);
                        fclose(fp);
                        printf("Last time thru, opened 'Test' , read %ld\n", TestValue);

                  }


            }
      }
      printf("You can verify the value by doing this:\n\n\tdebug test\n\td\n\tq\n"
            "\n\tIn the file you will see 7b00 0000 as the first 4 bytes.\n"
            "\t0x7b is 123 (base 10)\n\n");
      printf("Test complete \n");
      return 1;
}

Just copy the whole thing to main.c and build it.  I uploaded the executable to:

http://www.geocities.com/CapeCanaveral/Hangar/8802/bf.zip

If it helps, I could use some points
0
 

Author Comment

by:oualide
ID: 1252853
To duneram


Send me the evaluation. I will give you the points
0
 
LVL 2

Accepted Solution

by:
duneram earned 100 total points
ID: 1252854
Source & Explanation presented below.   Take the source code i posted and save it to a file (main.c).  Then compile it and run.  It takes a number, writes the number as binary to a file and then manipulates the value a bit.
0

Featured Post

IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

Summary: This tutorial covers some basics of pointer, pointer arithmetic and function pointer. What is a pointer: A pointer is a variable which holds an address. This address might be address of another variable/address of devices/address of fu…
Windows programmers of the C/C++ variety, how many of you realise that since Window 9x Microsoft has been lying to you about what constitutes Unicode (http://en.wikipedia.org/wiki/Unicode)? They will have you believe that Unicode requires you to use…
Video by: Grant
The goal of this video is to provide viewers with basic examples to understand and use while-loops in the C programming language.
The goal of this video is to provide viewers with basic examples to understand and use switch statements in the C programming language.

760 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

19 Experts available now in Live!

Get 1:1 Help Now