0

sorry for my bad English.I'm new to Linux system programming and new to C programming as well.
I'm copying one file to another, but after copy they differ in size. For example, the original file is 112640 bytes long and its copy is 10240 bytes (10kb) smaller, only 102400 bytes.

The code for copying is

curr_size = 0;
fdesc_output = open(path, O_RDWR|O_CREAT|O_TRUNC, 0777);
fdesc_extra_file = open(path2, O_WRONLY|O_CREAT|O_TRUNC,0777);
int lseek_position = lseek(fdesc_output,0,SEEK_SET); // return to the beginning of file
while (curr_size < desired_filesize) { //desired filesize is 100kb
size_t result = read(fdesc_output, buffer, buffer_size);
if (result < 0) {
    perror ("Error reading file: ");
    exit(1);
  }
  curr_size+=result;
  write(fdesc_extra_file, buffer, buffer_size);
}
Groosha
  • 2,897
  • 2
  • 22
  • 38

2 Answers2

1

the while is stopping at 102400 which is 100kb (your desired_filesize variable)

You should make desired_filesize bigger

Or, without using a desired_filesize:

you can copy until you hit the end. To get the size of a file in C read more here How can I get a file's size in C?

If you want to keep copying by blocks (not byte by byte) you will have to divide the file size into blocks and be careful at the end if you need to make a smaller block.

Community
  • 1
  • 1
fersarr
  • 3,399
  • 3
  • 28
  • 35
  • or maybe I should change ````while (curr_size < desired_filesize)```` to ````while (curr_size <= desired_filesize)```` ? – Groosha Mar 26 '14 at 21:45
  • 4
    Or not rely in a desired filesize at all. You want a exact copy, just iterate until you read the original's end of file. – Paulo Bu Mar 26 '14 at 21:47
  • Could you please explain how can I check end of file? I'm totally noob – Groosha Mar 26 '14 at 21:47
1

Unless you are trying to accomplish your goal using read and write, you can use the standard C library functions fread and fwrite.

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

int main(int argc, char** argv)
{
   char* sourceFile = argv[1];
   char* destinationFile = argv[2];
   char buffer[BUFSIZ];
   int s;

   FILE* in = fopen(sourceFile, "rb");
   if ( in == NULL )
   {
      printf("Unable to open '%s' for reading from.\n", sourceFile);
      exit(1);
   }

   FILE* out = fopen(destinationFile, "wb");
   if ( out == NULL )
   {
      printf("Unable to open '%s' for writing to.\n", destinationFile);
      fclose(in);
      exit(1);
   }

   while ( !feof(in) && !ferror(in) )
   {
      s = fread(buffer, 1, BUFSIZ, in);
      if ( s > 0 )
      {
         s = fwrite(buffer, 1, s, out);
      }
   }

   fclose(out);
   fclose(in);
}
R Sahu
  • 204,454
  • 14
  • 159
  • 270
  • If you want the output file to exactly match the input file then open in binary mode (`"rb"` and `"wb"` respectively) – M.M Mar 26 '14 at 22:14
  • The loop with `feof` will be infinite if the file has a read error that is not end-of-file - instead , break when `fread` returns 0. – M.M Mar 26 '14 at 22:16