0

i have to copy a bitmap image file using a buffer. here is an example of what i need to do. i have to read different parts of a bitmap into the buffer first at once and then write it to the target file. when i read different parts into the buffer , the previous string gets overwritten and the last string that is read is only written. i dont want to use read and write function for every part that has to be written. please help me with the code.

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

void fskip(FILE *fp, int num_bytes) {
  int i;
  for (i = 0; i < num_bytes; i++)
    fgetc(fp);
}

int main() {
  FILE *fp, *fp1;

  fp = fopen("c:\\users\\tapan\\desktop\\splash.bmp", "rb");
  fp1 = fopen("c:\\users\\tapan\\desktop\\splash2.bmp", "wb");

  int *j;
  j = (int *)malloc(3000);

  int k = 223121;
  int *i = &k;

  fread(j, 2, 1, fp);

  fread(j, 10, 1, fp);
  fwrite(j, 12, 1, fp1);

  fclose(fp1);
  fclose(fp);

  getch();
}
3
  • 2
    Out of all the issues with this code, the one pertinent to your question is because the first fread writes to your buffer, but then the second fread also writes to that buffer, overwriting the original fread contents. Commented Aug 1, 2013 at 18:29
  • but how do i move the pointer in buffer so that it doesn't get overwritten? Commented Aug 1, 2013 at 18:32
  • 1
    You will need to use pointer arithmetic Commented Aug 1, 2013 at 18:33

1 Answer 1

2

First of all, I will try to address your specific question and avoid any comments about other things in the code.

It looks like the fread() and fwrite() statements are not correct. The following code might be more exact.

   int main() {
     FILE *fp, *fp1;

     fp = fopen("c:\\users\\tapan\\desktop\\splash.bmp", "rb");
     fp1 = fopen("c:\\users\\tapan\\desktop\\splash2.bmp", "wb");

     int *j;
     j = (int *) malloc(3000);

     int k = 223121;
     int *i = &k;

     // read 2 items of sizeof(int) into j from fp
     fread(j, sizeof(int), 2, fp);

     // read 10 items of sizeof(int) into j + 2 from fp
     fread(j+2, sizeof(int), 10, fp);

     // write 12 items of sizeof(int) from j to fp1
     fwrite(j, sizeof(int), 12, fp1);

     fclose(fp1);
     fclose(fp);

     getch();
   }
   // Note. The above code has NOT been tested, it is thrown-up here for discussion.

Format of fread() and fwrite() is per K&R, second edition, page 247.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.