Search code examples
ccopyfwrite

Copy textfile using fwrite, ending up with trash? C


Iam trying to copy a text file to a new file. I was thinking that if I want to do it smart, I just copy everything binary so the copy will be identical to the first. However I'am ending up with weird character in the new document.

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

int main(int argc, char * argv[])
{
    FILE * fporgi, * fpcopy;


    if((fporgi = fopen(argv[1], "rb")) == NULL){
            //Error checking
        fprintf(stdout, "Error occurred trying to open file :%s", argv[1]);
        exit(EXIT_FAILURE);
    }
    if((fpcopy = fopen(argv[2], "wb")) == NULL){
        fprintf(stdout, "Error occurred trying to open file :%s", argv[2]);
        exit(EXIT_FAILURE);
    }

    long bytes;

    fseek(fporgi, 0L, SEEK_END); 
    bytes = ftell(fporgi);
    fprintf(stdout, "\n%ld\n", bytes);

    unsigned char buffer[bytes]; 
    fprintf(stdout, "\n%u\n", sizeof(buffer));
    fread(buffer, sizeof(buffer), 1, fporgi); 
    fwrite(buffer, sizeof(buffer), 1, fpcopy);

    fclose(fporgi);
    fclose(fpcopy);

    return 0;
}

Example if the original file contains "hej svej" the new file will have : "(œÌuR0@NUL"


Solution

  • You need to seek back to the start of the file after reading the length:

    fseek(fporgi, 0L, SEEK_END); 
    bytes = ftell(fporgi);
    fprintf(stdout, "\n%ld\n", bytes);
    fseek(fporgi, 0L, SEEK_SET);