]> Devi Nivas Git - cs3210-lab0.git/commitdiff
Finish part 1: Hello World
authorAdvaith Menon <noreply-git@bp4k.net>
Wed, 14 Jan 2026 21:36:03 +0000 (03:06 +0530)
committerAdvaith Menon <noreply-git@bp4k.net>
Wed, 14 Jan 2026 21:36:03 +0000 (03:06 +0530)
* Write code to create a temporary file first
* The code then reds from this file if it already exists

user/src/lab0/helloworld.c

index f054b31e0be9feb514f492f48dc0a2232853b0ed..a49e796f63d016ce600ee7c89a47e81c79315f67 100644 (file)
@@ -3,10 +3,43 @@
 #include "user.h"
 #include "fcntl.h"
 
+/* defines the temporary file hello world is written to */
+#define TEMPFILE "/tmpfile"
+
+/* define standard file descriptors - no magic numbers in code */
+#define STDIN_FD 0
+#define STDOUT_FD 1
+#define STDERR_FD 2
+
+#define LEN_HELLOWORLD 13
+#define LEN_DISCLAIMER 26
+
 int
 main(int argc, char *argv[])
 {
-  // Student code goes here
+  /* Student code goes here */
+
+    /* part (a): write "Hello, World" */
+
+    /* note file is created only when O_CREATE is specified! */
+    /* first try opening the file  without O_CREATE */
+    int fd = open(TEMPFILE, O_RDONLY);
+
+    /* if no issue, read its contents and close that same file */
+    if (fd >= 0) {
+        /* since no libc no need to worry about \0, treat like binary data,
+         * we anyway supply size */
+        char hellostr[LEN_HELLOWORLD];
+        read(fd, hellostr, LEN_HELLOWORLD);
+        write(STDOUT_FD, hellostr, LEN_HELLOWORLD);
+        close(fd);
+    } else {
+        /* if there is an issue, create the file! */
+        write(STDOUT_FD, "First run - creating file\n", LEN_DISCLAIMER);
+        int wfd = open(TEMPFILE, O_CREATE | O_WRONLY);
+        write(wfd, "Hello World!\n", LEN_HELLOWORLD);
+        close(wfd);
+    }
 
   exit();
-}
\ No newline at end of file
+}