
| int creat(const char *filename, mode_t mode); |
| int umask(int newmask); |
| int open(const char *pathname, int flags); int open(const char *pathname, int flags, mode_t mode); |
| 标志 | 含义 |
| O_RDONLY | 以只读的方式打开文件 |
| O_WRONLY | 以只写的方式打开文件 |
| O_RDWR | 以读写的方式打开文件 |
| O_APPEND | 以追加的方式打开文件 |
| O_CREAT | 创建一个文件 |
| O_EXEC | 如果使用了O_CREAT而且文件已经存在,就会发生一个错误 |
| O_NOBLOCK | 以非阻塞的方式打开一个文件 |
| O_TRUNC | 如果文件已经存在,则删除文件的内容 |
| 标志 | 含义 |
| S_IRUSR | 用户可以读 |
| S_IWUSR | 用户可以写 |
| S_IXUSR | 用户可以执行 |
| S_IRWXU | 用户可以读、写、执行 |
| S_IRGRP | 组可以读 |
| S_IWGRP | 组可以写 |
| S_IXGRP | 组可以执行 |
| S_IRWXG | 组可以读写执行 |
| S_IROTH | 其他人可以读 |
| S_IWOTH | 其他人可以写 |
| S_IXOTH | 其他人可以执行 |
| S_IRWXO | 其他人可以读、写、执行 |
| S_ISUID | 设置用户执行ID |
| S_ISGID | 设置组的执行ID |
| open("test", O_CREAT, 10705); |
| open("test", O_CREAT, S_IRWXU | S_IROTH | S_IXOTH | S_ISUID ); |
| int read(int fd, const void *buf, size_t length); int write(int fd, const void *buf, size_t length); |
| int open(pathname, O_CREAT | O_WRONLY | O_TRUNC, mode); |
| int lseek(int fd, offset_t offset, int whence); |
| lseek(fd, -5, SEEK_CUR); |
| lseek(fd, 0, SEEK_END); |
| int close(int fd); |
| #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <stdio.h> #define LENGTH 100 main() { int fd, len; char str[LENGTH]; fd = open("hello.txt", O_CREAT | O_RDWR, S_IRUSR | S_IWUSR); /* 创建并打开文件 */ if (fd) { write(fd, "Hello, Software Weekly", strlen("Hello, software weekly")); /* 写入 Hello, software weekly字符串 */ close(fd); } fd = open("hello.txt", O_RDWR); len = read(fd, str, LENGTH); /* 读取文件内容 */ str[len] = '\0'; printf("%s\n", str); close(fd); } |
![]() |
| FILE *fopen(const char *path, const char *mode); |
| 标志 | 含义 |
| r, rb | 以只读方式打开 |
| w, wb | 以只写方式打开。如果文件不存在,则创建该文件,否则文件被截断 |
| a, ab | 以追加方式打开。如果文件不存在,则创建该文件 |
| r+, r+b, rb+ | 以读写方式打开 |
| w+, w+b, wh+ | 以读写方式打开。如果文件不存在时,创建新文件,否则文件被截断 |
| a+, a+b, ab+ | 以读和追加方式打开。如果文件不存在,创建新文件 |
| int fgetc(FILE *stream); int fputc(int c, FILE *stream); char *fgets(char *s, int n, FILE *stream); int fputs(const char *s, FILE *stream); int fprintf(FILE *stream, const char *format, ...); int fscanf (FILE *stream, const char *format, ...); size_t fread(void *ptr, size_t size, size_t n, FILE *stream); size_t fwrite (const void *ptr, size_t size, size_t n, FILE *stream); |
| int fgetpos(FILE *stream, fpos_t *pos); int fsetpos(FILE *stream, const fpos_t *pos); int fseek(FILE *stream, long offset, int whence); 等。 |
| int fclose (FILE *stream); |
| #include <stdio.h> #define LENGTH 100 main() { FILE *fd; char str[LENGTH]; fd = fopen("hello.txt", "w+"); /* 创建并打开文件 */ if (fd) { fputs("Hello, Software Weekly", fd); /* 写入Hello, software weekly字符串 */ fclose(fd); } fd = fopen("hello.txt", "r"); fgets(str, LENGTH, fd); /* 读取文件内容 */ printf("%s\n", str); fclose(fd); } |