I am trying to write a program in c that copies the contents of a file into another one multiple times but something is off. Some weird characters appear, and it only copies once.
c code
#include <stdlib.h>
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
char* laod_with_correct_size(char* file_location, int size) {
char* buffer=NULL;
FILE* file;
size=0;
int len;
file=fopen(file_location,"rb");
if(file==NULL) {
fclose(file);
return NULL;
}
fseek(file,0,SEEK_END);
len=ftell(file);
if(len<1) {
fclose(file);
return NULL;
}
rewind(file);
buffer=(char*) malloc(len);
if(buffer==NULL) {
fclose(file);
return NULL;
}
if(fread(buffer,1,len,file)!=(size_t)len) {
free(buffer);
fclose(file);
return NULL;
}
fclose(file);
size=len;
printf("Size in fucntion is %d\n",len);
return buffer;
}
int get_size(char* filepath) {
FILE* f;
int len;
f=fopen(filepath,"rb");
fseek(f,0,SEEK_END);
len=ftell(f);
fclose(f);
printf("TOTAL SIZE THAT SHOULD BE IN THE FUCNTION IS %d",len);
}
int write_correctly(char* file,char* buffer,int len) {
// printf("len size is %d\n",len);
int file_descriptor = open(file,O_APPEND || O_CREAT);
int len_to_use=get_size(file);
int size=write(file_descriptor,buffer,len_to_use);
printf("Second size in fucntion is %d\n",size);
close(file_descriptor);
printf("SIZE OF SIZE+1 IS %d and SIZE OF LEN IS %d\n",size+1,len);
if(size!=len) {
return-1;
} else {
return size;
}
}
int main(int argc,char** argv) {
int size=0;
size=get_size(argv[1]);
char* buffer=laod_with_correct_size(argv[1],size);
printf("Size of %s is %d\n",argv[1],size);
// if(write_correctly(argv[2],buffer,size)<0) {
// printf("Couldn't write\n");
// }
write_correctly(argv[2],buffer,size);
write_correctly(argv[2],buffer,size);
write_correctly(argv[2],buffer,size);
write_correctly(argv[2],buffer,size);
return 0;
}
first file(to copy from)
salut
buna
alo
second file(to copy to)
salut
buna
alo
\00\00\00\00\00\00\00\00\00Q\F7\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00
My pointers are rusty but I hope I didn't make any huge mistakes.