|
gcc选项 -c 编译成模块文件.o -o 指定输出文件名 -g 加入调试信息 -D 在编译命令行中定义宏 -I 指定包含头文件目录 -O2二级优化 -Wall 打开警告信息 打开/关闭文件 <sys/types.h> <sys/stat.h> <fcntl.h> int open(const char *path,int flags,...); <unistd.h> int close(int fd); 标志位 O_RDONLY 只读打开 O_WRONLY 只写打开 O_RDWR 读写打开 O_NONBLOCK 不阻塞打开 O_APPEND 追加 O_CREAT 创建 O_TRUNC 截取为空 错误代码 <errno.h> 全局变量errno 格式化成字符串输出strerror(errno) 权限位umask 读r写w执行x 所有者u(user)组权限g(group)其他人o(other) 权限位的C宏 S_ISUID设置用户ID S_ISGID设置组ID S_IRWXU所有者的读写执行 S_IRUSR所有者的读 S_IWUSR所有者的写 S_IXUSR所有者的执行 S_IRWXG组的读写执行 S_IRGRP组的读 S_IWGRP组的写 S_IXGRP组的执行 S_IRWXO其他人的读写执行 S_IROTH其他人的读 S_IWOTH其他人的写 S_IXOTH其他人的执行 对umask的查询和设置 <sys/types.h> <sys/stat.h> mode_t umask(mode_t new_umask); 例:设置新的umask权限位并保存旧的 int old_mask; old_mask=umask(0077); 例:查询当前umask位 #include <stdio.h> #include <sys/types.h> #include <sys/stat.h> mode_t query_umask(void) { mode_t cu_umask; cu_umask=umask(0); return cu_umask; } int main(void) { printf("umask=%04o\n",query_umask()); return 0; } 创建文件 <fcntl.h> int create(const char *path,mode_t mode); 等价于 open(path,O_CREAT|O_TRUNC|O_WRONLY,mode); 读写 <sys/types.h> <sys/uio.h> <unistd.h> ssize_t read(int fd,void *buf,size_t count); ssize_t write(int fd,void *buf,size_t count); 其中sszie_t定义在types.h文件中,表示为signed size 简单的I/O例程 #include <stdio.h> #include <unistd.h> #include <errno.h> #include <fcntl.h> #include <string.h> int main(int argc,char **argv) { int n,fd; char buf[1024]; if(argc!=2) { printf("Usage:Test filename.\n"); exit(1); } if((fd=open(argv[1],O_CREAT|O_TRUNC|O_WRONLY))==-1) { printf("open %s file error,errorcode:%s\n",argv[1],strerror(errno)); exit(1); } strcpy(buf,"unix advanced programming\n"); buf[strlen(buf)]=0; printf("%d all bytes\n",strlen(buf)); if(write(fd,buf,strlen(buf)==-1) printf("write error,errorcode:%s\n",strerror(errno)); close(fd); return 0; } 文件读定指针定位 <sys/types.h> <unistd.h> off_t lseek(int fd,off_t offset,int whence); SEEK_SET 文件开始处 SEEK_CUR 文件当前处 SEEK_END 文件未尾处 例:获取当前位置 off_t offset; int fd; offset=lseek(fd,0,SEEK_CUR); 例:定位读到上个例子产生的文件 unix advanced programming 读取unix字符 #include <sys/types.h> #include <unistd.h> #include <stdio.h> #include <fcntl.h> int main(void) { int fd; char buf[5]; fd=open("./hello",O_RDONLY); lseek(fd,0,SEEK_SET); read(fd,buf,sizeof(buf-1)); buf[sizeof(buf)]=0; printf("Read from:%s\n",buf); return 0; } 截取文件到指定的字节数 <sys/types.h> <unistd.h> int truncate(const char *path,off_t length); int ftruncate(int fd,off_t length); 例:截取刚才创建的hello到0字节,让它成为一个空文件 #include <unistd.h> #include <sys/types.h> int main(void) { off_t len; len=0; printf("now truncate hello to 0 byte\n"); if((truncate("./hello",len))!=-1) printf("truncate success\n"); return 0; }
|