1

My aim is to delete one ore more parts inside a binary file. I do this by only copying the needed parts to a second file. I have got two methods. The first one should append count bytes from File1 (with offset skip) to File2.

void copyAPart(struct handle* h, off_t skip, off_t count) {

 struct charbuf *fileIn = NULL;
 struct charbuf *fileOut = NULL;
 fileIn = charbuf_create();
 fileOut = charbuf_create();
 int fin, fout, x, i;
 char data[SIZE];

 charbuf_putf(fileIn,"%s/File1", h->directory);
 charbuf_putf(fileOut,"%s/File2", h->directory);

 fin = open(charbuf_as_string(fileIn), O_RDONLY);
 fout = open(charbuf_as_string(fileOut), O_WRONLY|O_CREAT, 0666);

 lseek(fin, skip, SEEK_SET);
 lseek(fout,0, SEEK_END);

 while(i < count){
   if(i + SIZE > count){
       x = read(fin, data, count-i);
    }else{
       x = read(fin, data, SIZE);
    }
    write(fout, data, x);
    i += x;
    }

 close(fout);
 close(fin);
 charbuf_destroy(&fileIn);
 charbuf_destroy(&fileOut);
}

The second method should then append the rest of File1 (from skip to end) to File2

void copyUntilEnd(struct handle* h, off_t skip) {

 struct charbuf *fileIn = NULL;
 struct charbuf *fileOut = NULL;
 fileIn = charbuf_create();
 fileOut = charbuf_create();
 int fin, fout, x, i;
 char data[SIZE];

 charbuf_putf(fileIn,"%s/File1", h->directory);
 charbuf_putf(fileOut,"%s/File2", h->directory);

 fin = open(charbuf_as_string(fileIn), O_RDONLY);
 fout = open(charbuf_as_string(fileOut), O_WRONLY|O_CREAT, 0666);

 lseek(fin, skip, SEEK_SET);
 lseek(fout,0, SEEK_END);
 x = read(fin, data, SIZE);

 while(x>0){
    write(fout, data, x);
    x = read(fin, data, SIZE);
  }

 close(fout);
 close(fin);
 charbuf_destroy(&fileIn);
 charbuf_destroy(&fileOut);
}

My questions are as follows:

  1. Why is this not working as expected?
  2. What would I need to change to use this on large files (>4GB) on 64Bit systems?

Thanks in advance

reencode
  • 33
  • 4

1 Answers1

1

Initialize i to 0.

Change the type of i to off_t and x to ssize_t.

Check the return value of read and write in copyAPart. If it is 0 you have reached EOF, if it is -1 an error has occured.

When it comes to large files, you need to check the manual of your compiler. It should specify whether you need to do anything extra to manipulate large files.

Klas Lindbäck
  • 33,105
  • 5
  • 57
  • 82