简体   繁体   English

使用memcpy()将一个文件的内容复制到另一文件

[英]Copy one file's content to other file using memcpy()

I need to copy file1 context to file2. 我需要将file1上下文复制到file2。 Here's my files file1 这是我的文件file1

My name is John

file2 文件2

I like water

so my resilt should be file2 所以我的重击应该是file2

I like water
My name is John

I have to use mmap and memcpy for this. 我必须为此使用mmapmemcpy 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 但是之后我的file2看起来像那样

 My name i

Why? 为什么? what's wrong? 怎么了?

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. 同样, stat的第一个参数是文件名而不是描述符。 If you have a descriptor you can use fstat instead. 如果有描述符,则可以改用fstat

When you pass r you pass it a non-terminated contents of the first file, leading to undefined behavior . 传递r ,传递的是第一个文件的非终止内容,从而导致未定义的行为 If you checked what stat returned you would probably have noticed it returned -1 as it failed. 如果检查了返回的stat您可能会注意到它由于失败而返回-1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM