1

I need to copy file1 context to file2. Here's my files file1

My name is John

file2

I like water

so my resilt should be file2

I like water
My name is John

I have to use mmap and memcpyfor this. So here what I do First I open both files

int da_open(const char *name){
   int dskr;
   dskr = open( name, O_RDWR );
   if( dskr == -1 ){
      perror( name );
      exit(1);
   }
   printf( "dskr1 = %d\n", dskr );
   return dskr;
}

Then I mmap my file's

void *da_mmap1( int d, int size ){
   void *a = NULL;
   a = mmap( NULL, size, PROT_WRITE | PROT_READ, MAP_SHARED, d, 0 );
   if( a == MAP_FAILED ){
      perror( "mmap failed" );
      abort();
   }
   return a;
}

and here's my memcpy

void *da_memcpy(void *str1, const void *str2, size_t n){
    return memcpy(str1, str2, n);
}

and my main

int main(int argc, char *argv[] ){
    struct stat fileStat;
    int st;
    int d1;
    int d2;
    void *r = NULL;
    void *w = NULL;
    if(argc == 3){
        d1 = da_open(argv[1]);
        d2 = da_open(argv[2]);
        r = da_mmap1(d1, SIZE);
        w = da_mmap1(d2, SIZE);
        st = stat(r, &fileStat);
        printf("Tik skaitoma: %d\n", fileStat.st_size);
        da_memcpy(w,r,fileStat.st_size);
        da_munamp(r, SIZE);
        da_munamp(w, SIZE);
        da_close(d1);
        da_close(d2);
    }
    return 0;
}

But after this my file2 looks like that

 My name i

Why? what's wrong?

alk
  • 69,737
  • 10
  • 105
  • 255
David
  • 3,055
  • 4
  • 30
  • 73
  • 2
    Do yourself a favour and switch on all compiler warnings (`-Wall -Wextra -pedantic` for gcc). Then as the **1st** step in debugging: Fix the code until no more warnings are issued. – alk May 07 '15 at 07:16
  • 1
    Also the call to `stat()` misses error handling. – alk May 07 '15 at 07:18
  • the 'SIZE' should be a calculated value, different for each file. For the input file, stat() will tell you how big to make the mmap. for the output file, stat() will tell you the original size of the file. the output mmap needs to be large enough to encompass the combined length of the input file+original length of output file. When copying the data from the input file to the output file, the output copy need to start after the existing data in the output file.. Both are text files, so suggest also inserting a space before inserting the input file contents – user3629249 May 09 '15 at 01:11

1 Answers1

4

You need to get the sizes of both files, and write the first one at the end of the second file.


Also, the first argument to stat is the file name and not a descriptor. If you have a descriptor you can use fstat instead.

When you pass r you pass it a non-terminated contents of the first file, leading to undefined behavior. If you checked what stat returned you would probably have noticed it returned -1 as it failed.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621