//這是一個使用read函數(shù)把目標(biāo)文件中數(shù)據(jù)讀出寫入到另外一個文件中的實(shí)例
//待讀出數(shù)據(jù)文件由argv1參數(shù)給,待寫入數(shù)據(jù)文件由argv2給出
#include
#include
#include
#define PERMS 0666
#define DUMMY 0
#define MAXSIZE 1024 //常數(shù)定義
int main(int argc, char *argv[])
{
int sourcefd, targetfd; //目標(biāo)文件和源文件的描述符
int readCounter = 0; //讀出的字符計(jì)數(shù)器
char WRBuf[MAXSIZE]; //讀寫緩沖區(qū)
if(argc!=3) //如果命令行參數(shù)不爭取正確
{
printf("Plz input the correct filename as './exam311ReadFun filename1 filename2'\n");
return 1;
}
if((sourcefd = open(*(argv+1),O_RDONLY,DUMMY))==-1) //如果源文件打開失敗
{
printf("Source file open error!\n");
return 2;
}
if((targetfd = open(*(argv+2), O_WRONLY|O_CREAT, PERMS))==-1) //如果目標(biāo)文件打開失敗
{
printf("Target file open error!\n");
return 3;
}
while(( readCounter = read(sourcefd, WRBuf, MAXSIZE))>0) //如果讀出來的數(shù)據(jù)大于0
{
if(write(targetfd, WRBuf,readCounter) != readCounter) //如果寫入的數(shù)據(jù)和讀出的數(shù)據(jù)不同
{
printf("Target file write error!\n"); //寫數(shù)據(jù)錯誤
return 4;
}
}
close(sourcefd); //關(guān)閉源文件
close(targetfd); //關(guān)閉目標(biāo)文件
return 0;
}
網(wǎng)站欄目:[Linux文件]使用read函數(shù)從文件讀取數(shù)據(jù)的實(shí)例
網(wǎng)站路徑:
http://weahome.cn/article/ihigsh.html