fork(3) download
  1. #include <stdio.h>
  2. #include <stdlib.h> //For exit()
  3. #include <sys/stat.h> //I/O
  4. #include <ctype.h>
  5. #include <fcntl.h>
  6. #include <unistd.h>
  7.  
  8. //Function Protos
  9. static void usage(void);
  10. void Output(int, char);
  11. int CreateFile(char *MyFile);
  12. int CreateFolder(char *MyFolder);
  13.  
  14. int main(int argc, char *argv[]){
  15. int file;
  16. char character;
  17. int mFlag = 0;
  18. int fFlag = 0;
  19. int c;
  20.  
  21. //Check if arguments are correct
  22. if(argc == 0){
  23. usage();
  24. exit(0);
  25. }
  26.  
  27. if (argc !=2){
  28. usage();
  29. exit(0);
  30. }
  31.  
  32. //Check if file exists OR if its a dir
  33. if(access(argv[1], F_OK) != -1){
  34. //Check if its a dir
  35. struct stat s;
  36. int err = stat(argv[1], &s);
  37. if ( S_ISDIR(s.st_mode)){
  38. printf("%s: Is a directory\n", argv[1]);
  39. exit(0); //Exit, we can't do anything witha dir
  40. }
  41.  
  42. //Open file
  43. file = open(argv[1], O_RDONLY);
  44. if (file == -1)
  45. perror("Open() Error");
  46. }
  47. else{
  48. perror("Error");
  49. exit(-1);
  50. }
  51.  
  52.  
  53. //Command line arg
  54. while((c = getopt (argc, argv, "mf")) != -1){
  55. switch(c)
  56. {
  57. case 'm':
  58. mFlag = 1;
  59. printf("!M\n");
  60. if(CreateFile(argv[2]) != 0){
  61. perror("Error");
  62. exit(-1);
  63. }
  64. exit(0);
  65. break;
  66.  
  67. case 'f':
  68. printf("!F\n");
  69. fFlag = 1;
  70. CreateFolder(argv[2]);
  71. exit(0);
  72. break;
  73.  
  74. case '?':
  75. if (isprint (optopt))
  76. fprintf (stderr, "Unknown option '-%c'\n", optopt);
  77. else
  78. fprintf(stderr, "Unknown option character '\\x%x'\n", optopt);
  79. return 1;
  80. break;
  81.  
  82. default:
  83. abort ();
  84. }
  85. }
  86.  
  87.  
  88. //Output file
  89. Output(file, character);
  90.  
  91. //Close
  92. if (close(file) != 0){
  93. perror("Close() Error");
  94. exit(-1);
  95. }
  96.  
  97. return 0;
  98. }
  99.  
  100. static void usage(){
  101. printf ("Usage: op [File] [Option]\n");
  102. printf ("-m Create the file\n");
  103. printf ("-f Create the folder\n");
  104. }
  105. void Output(int MyFile, char MyChar){
  106. while (read (MyFile, &MyChar, 1) == 1)
  107. printf("%c", MyChar);
  108. }
  109. int CreateFile(char *MyFile){
  110. printf("Creating File");
  111. if(open(MyFile, O_RDWR | O_CREAT, S_IRUSR | S_IRGRP | S_IROTH) == -1){
  112. printf("Error: Could not creat file\n");
  113. exit(-1);
  114. }
  115. return 0;
  116. }
  117. int CreateFolder(char *MyFolder){
  118. //Code
  119. return 0;
  120. }
Success #stdin #stdout 0s 2052KB
stdin
-m file
stdout
Usage: op [File] [Option]
-m	Create the file
-f 	Create the folder