////myuc.h
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<fcntl.h>
#include<string.h>
#include<sys/types.h>
#include<sys/mman.h>
#include<sys/stat.h>
#include<stdio.h> #include<stdlib.h> #include<unistd.h> //#include<sys/types.h> //#include<sys/stat.h> #include<string.h> #include<fcntl.h> int main(){ //系统会减去other组的写权限 int fd=open("open4.txt",O_RDWR|O_CREAT|O_TRUNC,0777); if(fd==-1) perror("open"),exit(-1);//连接两个语句 char buf[100]={}; strcpy(buf,"mybuff1\n"); write(fd,buf,strlen(buf)); printf("openok,fd=%d\n",fd); close(fd); int fd2=open("open4.txt",O_RDONLY); if(fd2==-1) perror("open read"),exit(-1); memset(buf,0,sizeof(buf)); int readcount=read(fd,buf,sizeof(buf)); printf("fd2:%d,readed(%d):%s\n",fd2,readcount,buf); close(fd2); fd2=open("a.out",O_RDONLY); if(fd2==-1) perror("open src"),exit(-1); fd=open("a.out1",O_RDWR|O_CREAT|O_TRUNC,0777); if(fd==-1) perror("write dest"),exit(-1); //readcount=0; while(1){ readcount=read(fd2,buf,sizeof(buf)); if(readcount==0) break; else if(readcount==-1){ perror("read src");break; } write(fd,buf,readcount); } //while(readcount>0); close(fd); close(fd2); printf("文件复制成功!\n"); return 0; }
#include "myuc.h" int main(){ int fd=open("b.txt",O_RDWR); if(fd==-1) perror("open"),exit(-1); char ch; read(fd,&ch,1); printf("%c\n",ch); read(fd,&ch,1); printf("%c\n",ch); lseek(fd,7,SEEK_SET); read(fd,&ch,1); printf("%c\n",ch); lseek(fd,0,SEEK_SET);//回到开始 write(fd,"1",1);//替换a lseek(fd,3,SEEK_SET); write(fd,"2",1);//替换d lseek(fd,-2,SEEK_END);//注意最后的\n,也是一个字节 write(fd,"3",1);//替换到数第二个 int len=lseek(fd,0,SEEK_END);//文件大小 close(fd); return 0; }
#include<stdio.h> #include<stdlib.h> #include<unistd.h> //#include<sys/types.h> //#include<sys/stat.h> #include<string.h> #include<fcntl.h> typedef struct EMP{ int id; char name[100]; double salary; }emp; int main(){ int fd=open("write4.txt",O_CREAT|O_RDWR|O_APPEND,0777); if(fd==-1) perror("open"),exit(-1); printf("请输入编号,姓名,薪水:\n"); emp em; scanf("%d%s%lf",&em.id,em.name,&em.salary); int res=write(fd,&em,sizeof(emp)); if(res==-1) printf("失败\n"); else printf("成功!\n"); close(fd); fd=open("write4.txt",O_RDONLY); while(1) { res=read(fd,&em,sizeof(em)); if(res==0) break; else if(res==-1) { perror("read");break; } printf("%d,%s,%g\n",em.id,em.name,em.salary); } close(fd); return 0; }
#include<stdio.h> #include<stdlib.h> #include<unistd.h> #include<fcntl.h> void w1()//系统调用多,花时间多 { int fd=open("a.txt",O_CREAT|O_TRUNC,0777); if(fd==-1) perror("openwrite1"),exit(-1); int i; for(i=0;i<1000000;i++){ write(fd,&i,4); } } void w2(){//系统调用少,省时间 int fd=open("a.txt",O_RDWR|O_TRUNC); if(fd==-1) perror("openwrite2"),exit(-1); int arr[10000]; int i; for(i=0;i<1000000;i++){ arr[i%10000]=i; if(i%10000==9999) write(fd,arr,sizeof(arr));//10000个数字才写入一次 } close(fd); } int main() { //w1(); w2(); }