日期:2014-05-16 浏览次数:20761 次
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <fcntl.h> #include <unistd.h> #include <sys/types.h> int main() { int fd = open("a.txt", O_WRONLY | O_CREAT | O_TRUNC); if (fd == -1) perror(""), exit(-1); char buf[100] = {0}; /* define variables first */ int id = 3; char *name = "XX不哭,站起來擼!"; int age = 23; double salary = 8700.29; /* Chinese Yuan */ sprintf(buf, "%d\t%s\t%d\t%g", id, name, age, salary); write(fd, buf, sizeof(buf)); close(fd); /* 變量不定義在開始是C99支持的寫法,如果用gcc編譯器記得加“-std=c99”*/ int rid2; char rname2[20]; int rage2; double rsalary2; char id2[20], age2[20], salary2[20]; if((fd = open("a.txt", O_RDONLY)) < 0) { perror(""); exit(1); } read(fd, buf, sizeof(buf)); sscanf(buf, "%s\t%s\t%s\t%s", id2, rname2, age2, salary2); close(fd); rid2 = atoi(id2); rage2 = atoi(age2); rsalary2 = atof(salary2); printf("rid2: %d\n" "rname2: %s\n" "rage2: %d\n" "rsalary2: %g\n", rid2, rname2, rage2, rsalary2); }