I have file1.txt
This is my file
and file2.txt
This is my second file
and I want copy file2.txt content to file1.txt using memcpy
int main( int argc, char * argv[] ){
int d;
int d2;
int p;
FILE *f1;
FILE *f2;
if(argc == 3){
f1 = fopen(argv[1], "r+");
f2 = fopen(argv[2], "r+");
d = da_open(argv[1]);
d2 = da_open2(argv[2]);
p = da_cp(f2, f1, 10);
da_map(d, 10);
da_map(d2, 10);
close(p);
//closef(d2);
}
} I don't know why but when I run this I get file2.txt with lots of random symbols. Why? what I'm doing wrong?
EDIT: my full code
#include <stdio.h>
#include <stdlib.h>
#include <sys/mman.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/time.h>
#include <string.h>
int da_open(const char *name);
int da_open2(const char *name);
void *da_map(int d, int size);
int da_cp(void *str1, const void *str2, size_t n);
int da_open(const char *name){
int dskr;
dskr = open( name, O_RDONLY, 0640 );
if( dskr == -1 ){
perror( name );
exit( 255 );
}
printf( "dskr = %d\n", dskr );
return dskr;
}
int da_open2(const char *name){
int dskr;
dskr = open( name, O_RDWR, 0640 );
if( dskr == -1 ){
perror( name );
exit( 255 );
}
printf( "dskr = %d\n", dskr );
return dskr;
}
void *da_map(int d, int size){
void *a = NULL;
a = mmap( NULL, size, PROT_READ | PROT_WRITE, MAP_SHARED, d, 0 );
if( a == MAP_FAILED ){
perror( "mmap failed" );
abort();
}
return a;
}
int da_cp(void *str1, const void *str2, size_t n){
memcpy(str1, str2, n);
}
int main( int argc, char * argv[] ){
int d;
int d2;
int p;
FILE *f1;
FILE *f2;
if(argc == 3){
f1 = fopen(argv[1], "r+");
f2 = fopen(argv[2], "r+");
d = da_open(argv[1]);
d2 = da_open2(argv[2]);
p = da_cp(f2, f1, 10);
da_map(d, 10);
da_map(d2, 10);
close(p);
//closef(d2);
}
}