1. 程式人生 > >Linux C程式設計之IO-檔案拷貝

Linux C程式設計之IO-檔案拷貝

Linux C程式設計:IO

1.1檔案拷貝

本次檔案拷貝需要使用到如下三個函式原型:
開啟檔案
FILE * fopen(const char * path,const char * mode);
相關函式:open,fclose,fopen_s,_wfopen
返回值:檔案順利開啟後,指向該流的檔案指標就會被返回。如果檔案開啟失敗則返回NULL,並把錯誤程式碼存在errno 中。
讀、寫檔案
#include <stdio.h>
 size_t fread(void *ptr, size_t size, size_t nmemb, FILE *stream);
 size_t fwrite(const
void *ptr, size_t size, size_t nmemb, FILE *stream);

返回值
On success, fread() and fwrite() return the number of items read or written. This number equals the number of bytes transferred only when size is 1. If an error occurs, or the end of the file is reached, the return value is a short item count (or zero).fread() does not distinguish between end-of-file and error, and callers must use feof(3) and ferror(3) to determine which occurred.**

實現程式碼

//
// Created by 挽秋 on 3/23/17.
//
/*function : copy file from file1 to file2*/
#include <stdio.h>            /*fprinf(), stderr, BUFSIZE*/
#include <stdlib.h>
#include <string.h>         //stderror()
#include <fcntl.h>          //open(), flag
#include <errno.h>          //errno
#include <unistd.h> //ssize_t #include <sys/types.h> #include <sys/stat.h> //mode_t #define BUFFER_SIZE 3 int main(int argc, char **argv) { int inputFD, targetFD; int bytes_read, bytes_write; char buffer[BUFFER_SIZE]; char *ptr; if(argc != 3) { fprintf(stderr, "Usage: %s fromFile tofile\n\a", argv[0]); exit(1); } /*開啟原始檔*/ if( (inputFD = open(argv[1], O_RDONLY)) == -1) { //open file readonly,返回-1表示出錯,否則返回檔案描述符 fprintf(stderr, "Open %s Error: %s\n", argv[1], strerror(errno)); exit(1); } //建立目的檔案 // 使用了O_CREATE選項建立檔案,open()函式需要第三個引數 //mode = S_IRUSER|S_IWUSER表示S_ISUSR使用者可以讀S_IWUSR使用者可以寫 if( (targetFD = open(argv[2], O_WRONLY|O_CREAT, S_IRUSR|S_IWUSR))== -1) { fprintf(stderr, "Open %s Error: %s\n", argv[2], strerror(errno)); exit(1); } //進行檔案內容的拷貝 while (bytes_read = read(inputFD, buffer, BUFFER_SIZE)) { //檔案讀取發生錯誤 if( (bytes_read == -1)&& (errno != EINTR)) break; else if(bytes_read > 0) { ptr = buffer; while(bytes_write = write(targetFD, ptr, bytes_read)) { //寫內容發生錯誤 if( (bytes_write == -1) && errno != EINTR) break; else if(bytes_write > 0) { ptr += bytes_write; bytes_read -= bytes_write; } else if(bytes_read == bytes_write) break; } //寫檔案發生錯誤 if(bytes_write == -1) break; } } close(inputFD); close(targetFD); return 1; }