UNIX环境高级编程学习之第三章文件IO-文件写操作 #include <stdio.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> #include <stdlib.h> #include <string.h> #include <errno.h> int err_sys(const char * str) { printf("%s/n", str); exit(-1); return 0; } int main(int argc, char *argv[]) { int fd; // 只创建新文件,新文件权限主读 fd = open("./a.txt", O_RDWR|O_CREAT|O_EXCL, 0400); if (-1 == fd) { err_sys(strerror(errno)); } int i = 100; double d = 98.99; float f = 10.3; char c = 65; char str[100] = "wan zhen jie is hao ren"; int ret = write(fd, &i, sizeof(i)); if (ret != 4) { err_sys("write error!"); } ret = write(fd, &d, sizeof(double)); if (ret != sizeof(double)) { err_sys("write error! "); } ret = write(fd, &f, sizeof(f)); if (ret != sizeof(f)) { err_sys("write error!"); } ret = write(fd, &c, sizeof(c)); if (ret != sizeof(c)) { err_sys("write error!"); } ret = write(fd, str, sizeof(str)); if (ret != sizeof(str)) { err_sys("write error!"); } close(fd); }