功能:把源檔案的最後20KB位元組拷貝到目标檔案分10次完成
系統I/O:
#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>
#include<sys/types.h>
#include<fcntl.h>
#include<sys/stat.h>
//open write read lseek close 函數所在的頭檔案
#define BUFFER_SIZE 1024 /*每次讀寫緩存大小,影響運作效率*/
#define SRC_FILE_NAME "/home/yy/src_file" /*源檔案*/
#define DES_FILE_NAME "/home/yy/des_file" /*目标檔案*/
#define OFFSET 20480
int main()
{
int src_file,dest_file;
unsigned char buff[BUFFER_SIZE];
int real_get_length;
int times=10;
/*以隻讀的方式打開源檔案*/
src_file=open(SRC_FILE_NAME,O_RDONLY);
/*以隻寫的方式打開目标檔案,若此檔案不存在則建立*/
dest_file=open(DES_FILE_NAME,O_WRONLY|O_CREAT);
if(src_file<0||dest_file<0)
{
printf("Open file error\n");
exit(0);
}
/*将源檔案的讀寫指針移動到最後20kb的起始位置*/
lseek(src_file,-OFFSET,SEEK_END);
/*讀取源檔案的最後20kb資料并寫到目标檔案中,每次讀寫1kb,讀取10次*/
while((real_get_length=read(src_file,buff,sizeof(buff)))>0&×>0)
{
times--;
write(dest_file,buff,real_get_length);
}
close(dest_file);
close(src_file);
return 0;
}
标準I/O:
#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>
#include<sys/types.h>
#include<fcntl.h>
#include<sys/stat.h>
//open write read lseek close 函數所在的頭檔案
#define BUFFER_SIZE 1024 /*每次讀寫緩存大小,影響運作效率*/
#define SRC_FILE_NAME "/home/yy/src_file" /*源檔案*/
#define DES_FILE_NAME "/home/yy/des_file" /*目标檔案*/
#define OFFSET 20480
int main()
{
FILE *src_file,*dest_file;
unsigned char buff[BUFFER_SIZE];
int real_get_length;
int times=10;
src_file=fopen(SRC_FILE_NAME,r);//隻讀打開
dest_file=fopen(DES_FILE_NAME,w+);//沒有就建立
if(dest_file<0||src_file<0)
{
printf("error \n");
exit(0);
}
fseek(src_file,-OFFSET,SEEK_END);
while((real_get_length=fread(buff,1,sizeof(buff),src_file))>0||times>0)
{
times--;
fwrite(buff,1,read_get_length,dest_file);
}
fclose(dest_file);
fclose(src_file);
return 0;
}