Wednesday, February 26, 2014

C programming exercise: copy file

The following code copy file using C language, run in Raspberry Pi.

copy file using C

#include <fcntl.h>
#include <stdio.h>

int main(int argc, char *argv[]){
    int srcFileDesc;    //file descriptor of source file
    int destFileDesc;   //file descriptor of output file
    ssize_t numberOfRead;
    int BUFFER_SIZE = 1024;
    char buffer[BUFFER_SIZE];
    char *SRC_FILE ="test";
    char *DEST_FILE ="new_test";
    printf("Copy file %s to %s\n", SRC_FILE, DEST_FILE);
    printf("Open file: %s\n", SRC_FILE);
    srcFileDesc = open("test", O_RDONLY);
    if(srcFileDesc != -1){
        printf("Create output file: %s\n", DEST_FILE);
        destFileDesc = open(DEST_FILE,
        if(destFileDesc != -1){
            while((numberOfRead=read(srcFileDesc, buffer, BUFSIZ)) > 0){
                if(write(destFileDesc, buffer, numberOfRead) != numberOfRead){
                    printf("Error in copying...!\n");
            if(numberOfRead == -1){
                printf("Something wrong...!\n");
            if (close(destFileDesc) != -1){
                printf("Close destination file: %s\n", DEST_FILE);
                printf("Error in Close destination file: %s\n", DEST_FILE);
            printf("Error in Create output file: %s\n", DEST_FILE);
        if (close(srcFileDesc) != -1){
            printf("Close file: %s\n", SRC_FILE);
            printf("Error in Close file: %s\n", SRC_FILE);
        printf("Cannot open file: %s\n", SRC_FILE);

No comments: