返回值:当前读取在文件中的绝地位置
#include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> #include <stdlib.h> #include <stdio.h> //注意这里 为了以后读取方便 请人为对齐 不要让计算机来对齐 struct stu { int no; char name[16]; float score; }; int openfile(const char* filename) { int fd = open(filename,O_WRONLY|O_CREAT|O_EXCL,0666); if(fd < 0) { perror("open error!"); } return fd; } void input(struct stu *record) { printf("请输入学生ID:"); scanf("%d",&(record->no)); printf("请输入学生姓名:"); scanf("%s",record->name); printf("请输入学生成绩:"); scanf("%f",&(record->score)); } void save(int fd,struct stu* record) { write(fd,record,sizeof(struct stu)); } int iscontinue() { char c; printf("是否继续输入:y/n\n"); scanf("%c",&c); scanf("%c",&c); if(c == 'y') { return 1; } else return 0; } int main() { int fd =openfile("stu.dat"); if(fd < 0) { return 1; } struct stu record; while(1) { input(&record); save(fd,&record); if(! iscontinue() ) { break; } } close(fd); }
/*读取文件中的姓名 文件以结构体的形式写入 struct stu { int no; char name[16]; float score; }; */ #include <stdio.h> #include <unistd.h> #include <fcntl.h> #include <sys/types.h> int main() { int fd = open("stu.dat",O_RDONLY); if(fd < 0) { perror("open"); return 1; } int i = 0; char buf[4092]; lseek(fd,i*24+4,SEEK_SET); while(read(fd,buf,16)) { printf("%s ",buf); i++; lseek(fd,i*24+4,SEEK_SET); } printf("\n"); close(fd); }
#include <stdio.h> #include <unistd.h> #include <fcntl.h> #include <sys/types.h> int main() { int fd = open("dat",O_RDWR|O_CREAT,0666); if(fd < 0) { perror("open"); return 1; } int r = lseek(fd,2000,SEEK_SET); printf("%d\n",r); close(fd); }
#include <stdio.h> #include <unistd.h> #include <fcntl.h> #include <sys/types.h> int main() { int fd = open("dat",O_RDWR|O_CREAT,0666); if(fd < 0) { perror("open"); return 1; } int r = lseek(fd,2000,SEEK_SET); printf("%d\n",r); write(fd,"hello"5); close(fd); }
//读取文件中的姓名 #include <stdio.h> #include <unistd.h> #include <fcntl.h> #include <sys/types.h> int main() { int fd = open("stu.dat",O_RDONLY); if(fd < 0) { perror("open"); return 1; } int i = 0; char buf[4092]; while(pread(fd,buf,16,i*24+4)) { printf("%s ",buf); i++; } printf("\n"); close(fd); }
changed.
记住 都不改变读写位置 , 这就是它们和lseek+read/write的区别
#include <stdio.h> #include <unistd.h> #include <fcntl.h> #include <sys/types.h> #include <string.h> int a = 91119; int main() { char filename[20]; memset(filename,0,20); sprintf(filename,"/proc/%d/mem",getpid()); //mem文件 虚拟内存空间映射到mem上了 int fd = open(filename,O_RDWR); if(fd < 0) { perror("open error"); return 1; } //读取&a这个位置的地址 int t; pread(fd,&t,4,(off_t)&a); printf("t:%d\n",t); //91119 t = 88888; pwrite(fd,&t,4,(off_t)&a);//往所在a的地方写数据 printf("a=%d\n",a); //没有改变 因为系统没有给写的权限 }