rename.c 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  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 <unistd.h>
  4. #include <stdlib.h>
  5. #include <stdio.h>
  6. #include <errno.h>
  7. #include <sys/stat.h>
  8. #include <fcntl.h>
  9. #define TESTFILE "testfile"
  10. int main(int argc, char ** argv)
  11. {
  12. int ret = 0, fd;
  13. if ((ret = creat(TESTFILE, 0600)) < 0) {
  14. perror("creat");
  15. exit(1);
  16. }
  17. fd = ret;
  18. if ((ret = write(fd, "Hello World", 11)) < 0) {
  19. perror("write");
  20. exit(1);
  21. }
  22. close(fd);
  23. if ((ret = rename(TESTFILE, TESTFILE ".new")) < 0) {
  24. perror("rename");
  25. exit(1);
  26. }
  27. if ((ret = open(TESTFILE ".new", O_RDONLY)) < 0) {
  28. perror("open");
  29. exit(1);
  30. }
  31. fd = ret;
  32. char buffer[12];
  33. if ((ret = read(fd, buffer, 11)) < 0) {
  34. perror("read");
  35. exit(1);
  36. }
  37. buffer[11] = 0;
  38. printf("%s\n", buffer);
  39. close(fd);
  40. if ((ret = unlink(TESTFILE ".new")) < 0) {
  41. perror("unlink");
  42. exit(1);
  43. }
  44. return 0;
  45. }