1 创建一个新的文件,如果已经存在则删除其全部内容,重新从头开始写入。
#include <stdint.h>
#include <sys/types.h>
#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>
#include <fcntl.h>
int main() {
int fd = open("1", O_RDWR | O_CREAT | O_TRUNC, S_IRWXU);
char a[] = "abcdef";
write(fd, a, 6);
close(fd);
return EXIT_SUCCESS;
}
2 追加模式创建一个文件,如果已经存在则其末尾开始写入。
#include <stdint.h>
#include <sys/types.h>
#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>
#include <fcntl.h>
int main2() {
int fd = open("1", O_RDONLY, 0);
if (fd < 0) {
printf("error open");
exit(0);
}
printf("fd == %d\n", fd);
char *a = (char*) calloc(100, sizeof(char));
int size = read(fd, a, 5);
a[size] = '\0';
printf("%s\n", a);
printf("end\n");
close(fd);
free(a);
return EXIT_SUCCESS;
}
int main() {
int fd = open("1", O_RDWR | O_CREAT | O_APPEND, S_IRWXU);
char a[] = "abcdef";
write(fd, a, 6);
close(fd);
return EXIT_SUCCESS;
}