file.c 836 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. #include <stdio.h>
  2. #include <unistd.h>
  3. #include <fcntl.h>
  4. int main(int argc, char ** argv)
  5. {
  6. int fd1 = creat("testfile", 0600);
  7. if (fd1 < 0) {
  8. perror("creat");
  9. return 1;
  10. }
  11. write(fd1, "Hello World\n", 12);
  12. close(fd1);
  13. int fd2 = open("testfile", O_RDONLY, 0600);
  14. if (fd2 < 0) {
  15. perror("open without O_CREAT");
  16. return 1;
  17. }
  18. char buffer[20];
  19. int bytes = read(fd2, buffer, 20);
  20. if (bytes < 0) {
  21. perror("read");
  22. return 1;
  23. }
  24. buffer[11] = 0;
  25. printf("read from file: %s\n", buffer);
  26. close(fd2);
  27. unlink("testfile");
  28. int fd3 = open("testfile", O_RDWR|O_CREAT|O_EXCL, 0600);
  29. if (fd3 < 0) {
  30. perror("open with O_CREAT and O_EXCL");
  31. return 1;
  32. }
  33. close(fd3);
  34. unlink("testfile");
  35. return 0;
  36. }