Solved

How to read,process & write a binary file?

Posted on 1998-09-17
12
9,570 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
Netscaler Common Configuration How To guides

If you use NetScaler you will want to see these guides. The NetScaler How To Guides show administrators how to get NetScaler up and configured by providing instructions for common scenarios and some not so common ones.

 
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
 

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

Master Your Team's Linux and Cloud Stack!

The average business loses $13.5M per year to ineffective training (per 1,000 employees). Keep ahead of the competition and combine in-person quality with online cost and flexibility by training with Linux Academy.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Preface I don't like visual development tools that are supposed to write a program for me. Even if it is Xcode and I can use Interface Builder. Yes, it is a perfect tool and has helped me a lot, mainly, in the beginning, when my programs were small…
This tutorial is posted by Aaron Wojnowski, administrator at SDKExpert.net.  To view more iPhone tutorials, visit www.sdkexpert.net. This is a very simple tutorial on finding the user's current location easily. In this tutorial, you will learn ho…
The goal of this video is to provide viewers with basic examples to understand and use pointers 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.

773 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