文件IO函数实现拷贝文件。子进程先拷贝后半部分,父进程再拷贝前半部分,允许使用sleep函数
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<head.h>
int main(int argc, const char *argv[])
{pid_t cpid=fork();int fd=open("./1.c",O_RDONLY);if(fd<0){ERR_MSG("open");return -1;}printf("open success\n");off_t size=lseek(fd,0,SEEK_END);lseek(fd,0,SEEK_SET);char buf[20]="";ssize_t res=0;if(cpid>0){sleep(1);while(1){bzero(buf,sizeof(buf));off_t size1=lseek(fd,0,SEEK_CUR);if(size1>=size/2)break;res=read(fd,buf,sizeof(buf)-1);printf("%s",buf);}}else if(cpid==0){lseek(fd,size/2,SEEK_SET);while(1){bzero(buf,sizeof(buf));res=read(fd,buf,sizeof(buf)-1);if(0==res){break;}printf("%s",buf);}}else{perror("fork");return -1;}close(fd);while(1)sleep(1);return 0;
}
从终端获取一个文件的路径以及名字
若该文件是目录文件,则将该文件下的所有文件的属性显示到终端,类似ls -l该文件
若该文件不是目录文件,则显示该文件的属性到终端上,类似ls -l该文件
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<head.h>
void get_filePrmission(mode_t m)
{int a=0400;while(a){if((m&a)!=0)putchar('r');elseputchar('-');a=a>>1;if((m&a)!=0)putchar('w');elseputchar('-');a=a>>1;if((m&a)!=0)putchar('x');elseputchar('-');a=a>>1;}return;
}
void get_fileType(mode_t m)
{if(S_ISREG(m))putchar('-');else if(S_ISDIR(m))putchar('d');else if(S_ISCHR(m))putchar('c');else if(S_ISBLK(m))putchar('b');else if(S_ISFIFO(m))putchar('p');else if(S_ISLNK(m))putchar('l');elseputchar('s');return;
}
void get_localtime(time_t t)
{struct tm* info=NULL;info=localtime(&t);printf("%4d-%02d-%02d %02d:%02d:%02d",info->tm_year+1900,\info->tm_mon+1,info->tm_mday,info->tm_hour,\info->tm_min,info->tm_sec);fflush(stdout);
}
int wjsxsc(struct stat buf)
{get_fileType(buf.st_mode);get_filePrmission(buf.st_mode);struct passwd *pwd=getpwuid(buf.st_uid);if(NULL==pwd){ERR_MSG("getpwuid");return -1;}printf(" %s ",pwd->pw_name);struct group *gid=getgrgid(buf.st_gid);if(NULL==gid){ERR_MSG("getgrgid");return -1;}printf("%s",gid->gr_name);printf(" %ld ",buf.st_size);get_localtime(buf.st_ctime);
}
int main(int argc, const char *argv[])
{char l[20]="";printf("输入一个文件的路径及名字");scanf("%s",l);struct stat buf;if(stat(l,&buf)<0){ERR_MSG("stat");return -1;}if(S_ISDIR(buf.st_mode)){DIR *fp=opendir(l);if(NULL==fp){ERR_MSG("opendir");return -1;}printf("opendir success");int i=1;while(1){struct dirent *rp=readdir(fp);if(NULL==rp){if(0==errno){printf("文件读取成功\n");break;}else{ERR_MSG("readdir");return -1;}}if(stat(rp->d_name,&buf)<0){ERR_MSG("stat");return -1;}wjsxsc(buf);printf(" %s\n",rp->d_name);}if(closedir(fp)<0){ERR_MSG("closedir");return -1;}}else{wjsxsc(buf);printf(" %s\n",l);}return 0;
}