文档详情

Unix环境编程笔记3.pdf

发布:2017-07-15约9.38千字共21页下载文档
文本预览下载声明
day3 linux 文件系统 1.文件 一切都是文件 - /dev/console 控制台 - /dev/tty 终端 (键盘,显示器。。。。) - /dev/null 空设备文件(unix 黑洞) cat /dev/null a.txt 相当于清空a.txt find 找 open.c #includestdio.h #includefcntl.h #includesys/types.h #includesys/stat.h int main() { int fd = open( a.txt ,O_RDWR | O_CREAT,0666 ); if(fd == -1) { perror( failed ); exit(1); } printf( 打开成功fd = %d\n ,fd); int fd2 = open( b.txt ,O_RDWR | O_CREAT | O_TRUNC /*| O_EXEC*/,0666) ; if(fd2 == -1) { perror( 创建文件失败 ) ; exit(-1); } printf( 创建文件成功fd2 = %d\n ,fd2); } 读写文件 eg: write.c #includestdio.h #includefcntl.h #includeunistd.h #includestring.h #includestdlib.h int main() { int fd = open ( a.txt ,O_WRONLY); if(fd == -1) perror( failed ),exit(-1); int id = 100; char *name = Daniel ; double salary = 123456.78 int res = write(fd,id,sizeof(id)); if(res = 0) perror( faild ); write(fd,name,strlen(name)); write(fd,salary,sizeof(salary)); write(1, hello ,5);//写到显示器 close(fd); } eg:read.c #includestdio.h #includefcntl.h #includestdlib.h #includestring.h int main() { int fd = open( a.txt ,O_READ); if (-1 == fd) { perror( failed ); exit(-1); } int id; int res = read(fd,id,sizeof(id)); if(-1 == res) perror( 读取失败 ); else printf( 读取到%d字节数据\n ,res); //char *name = malloc(100); 也行 char name[100]= {}; read(fd,name,6); double salary; read(fd,salary,sizeof(salary)); printf( %d,%s,%lf ,id,name,salary); close(fd); } man read 看read命令 man 2 read / man -s2 read 看read函数 eg: rw.c #includestdio.h #includefcntl.h #includeunistd.h #includestring.h #includestdlib.h struct emp { int id; char name[10]; double salary; }; int main() { struct emp e = {100, Daniel , 123456.78}; int fd = open( emp.txt ,O_WRONLY|O_CREAT |O_TRUNC,0666) if(-1 ==
显示全部
相似文档