2022年5月15日 星期日

[C/C++] 使用read/write拷貝檔案範例

說明:
使用read/write拷貝檔案範例

Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>

#define BOOL                    int
#define TRUE                    0
#define FALSE                   -1
#define MAX_LONG_LENGTH         1024
#define MAX_SHORT_LENGTH        128

BOOL copyfile_fun(char *src, char *dest)
{
    int  ret = TRUE;
    int  len = 0;;
    char buffer[MAX_LONG_LENGTH];

    int fd1 = open(src, O_RDONLY);
    int fd2 = open(dest, O_RDWR|O_CREAT, S_IRWXU);
   
    while((len = read(fd1, buffer, MAX_LONG_LENGTH)) > 0)
    {
        if (write(fd2, buffer, len) != len)
        {
            printf("[ERROR] write file %s failed\n", dest);    
            ret = FALSE;
            break;
        }
    }
          
    if (fd1) close(fd1);
    if (fd2) close(fd2);
   
    return ret;
}

int main(int argc, char *argv[])
{
    if (copyfile_fun("/etc/exports", "./exports") == TRUE)
        printf("[SUCCESS] copy file successfully!\n");
    else
        printf("[ERROR] copy file failed!\n");

    return 0;
}

Result:
[SUCCESS] copy file successfully!


沒有留言:

張貼留言