file.c 1.0 KB

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