#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>
#include <strings.h>
#include <sys/types.h>
#include <sys/stat.h>
#define BUFFERSIZE 1024
typedef int fid_t;
int main(int argc,char **argv){
fid_t fd1=0;
fid_t fd2=0;
int readBytes=0;
char *buffer=NULL;
buffer=(char*)malloc(BUFFERSIZE*sizeof(char));
memset(buffer,0,BUFFERSIZE*sizeof(char));
fd1=open("/etc/passwd",O_RDONLY);
if(fd1<0){
perror("open(fd1)");
exit(1);
}
fd2=open("passwd.bak",O_CREAT|O_RDWR|O_EXCL,0644);
if(fd2<0){
perror("open(fd2)");
exit(1);
}
while((readBytes=read(fd1,buffer,BUFFERSIZE))>0){
if(write(fd2,buffer,BUFFERSIZE)<0){
perror("write(fd2)");
exit(1);
}
memset(buffer,0,BUFFERSIZE*sizeof(char));
}
if(readBytes<0){
perror("read(fd1)");
exit(1);
}
close(fd1);
close(fd2);
exit(0);
}
copy1.c 复制文件
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <dirent.h>
#include <errno.h>
DIR *opendir(const char *name);
int main(int argc,char **argv){
int ret=0;
int count=0;
DIR *dp;
struct dirent *dirent;
if(argc!=2){
printf("usage:readdir<staring-pathname>\n");
exit(1);
}
dp=opendir(argv[1]);
if(dp==NULL){
perror("opendir()");
exit(1);
}
while((dirent=readdir(dp))!=NULL){
count++;
printf("file[%2d]:->%s\n",count,dirent->d_name);
}
if(errno){
perror("readdir()");
exit(1);
}
exit(0);
}
readdir1.c读目录下的文件