Unsupported file after duplicating it

Viewed 32

I wrote a VERY simple program that copies all the bytes from a selected file and write them in a new/selected file. What I want to do is duplicate 'elaborate' (encoded) file such .jpg, .png, .mp3, .exe and so on... The program works fine (especially using simple .txt file), here is a running example:

(Wrote and compiled in windows using mingw):

C:\Users\Computer\Desktop>duplicate.exe img.jpg file.txt

Content of file.txt:

ÿØÿà JFIF      ÿÛ C 


        

If file.txt would have been substituted with <filename>.<new_file_extention>, the program would have create the new file and copied the above content inside as in:

C:\Users\Computer\Desktop>duplicate.exe img.jpg new_img.jpg

When I try to open new_img.jpg though the OS says me that the file is not supported hence cannot be opened.

My reasoning before writing the program was the following: "At bottom level any file is just a sequence of bytes, hence copying from an existing file and pasting onto a brand new/selected file will result in actually duplicating the file avoiding any type of encoding."

Here is the code:

//The program is just a test, is not a final version, hence the absence of some error handling. 
#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>

#define MAXBYTE     2500
#define RDWRMAX     1024

int main(int argc, char **argv){
    int ifd, ofd, n;
    char buf[MAXBYTE+1];

    if((ifd = open(*++argv, O_RDONLY, 0)) == -1){
        fprintf(stderr, "Unable to open '%s'.\n", *argv);
        exit(EXIT_FAILURE);
    }
    if((ofd = open(*++argv, O_WRONLY | O_CREAT, 0)) == -1){
        fprintf(stderr, "Unable to open '%s'.\n", *argv);
        exit(EXIT_FAILURE);
    }

    while((n = read(ifd, buf, RDWRMAX)) > 0)
        write(ofd, buf, n);
}

Can anyone help me understand why this is happening and maybe suggesting some possible way to solve it? This is a learning process for me, so thanks in advance for all the useful answers to this question.

0 Answers
Related