file.c 1012 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. /* -*- mode:c; c-file-style:"k&r"; c-basic-offset: 4; tab-width:4; indent-tabs-mode:nil; mode:auto-fill; fill-column:78; -*- */
  2. /* vim: set ts=4 sw=4 et tw=78 fo=cqt wm=0: */
  3. #include <stdio.h>
  4. #include <unistd.h>
  5. #include <fcntl.h>
  6. int main(int argc, char ** argv)
  7. {
  8. int fd1 = creat("testfile", 0600);
  9. if (fd1 < 0) {
  10. perror("creat");
  11. return 1;
  12. }
  13. write(fd1, "Hello World\n", 12);
  14. close(fd1);
  15. int fd2 = open("testfile", O_RDONLY, 0600);
  16. if (fd2 < 0) {
  17. perror("open without O_CREAT");
  18. return 1;
  19. }
  20. char buffer[20];
  21. int bytes = read(fd2, buffer, 20);
  22. if (bytes < 0) {
  23. perror("read");
  24. return 1;
  25. }
  26. buffer[11] = 0;
  27. printf("read from file: %s\n", buffer);
  28. close(fd2);
  29. unlink("testfile");
  30. int fd3 = open("testfile", O_RDWR|O_CREAT|O_EXCL, 0600);
  31. if (fd3 < 0) {
  32. perror("open with O_CREAT and O_EXCL");
  33. return 1;
  34. }
  35. close(fd3);
  36. unlink("testfile");
  37. return 0;
  38. }