From 59b91148add89c495222fa38464ce57beb4a1ecf Mon Sep 17 00:00:00 2001 From: Advaith Menon Date: Thu, 15 Jan 2026 03:06:03 +0530 Subject: [PATCH] Finish part 1: Hello World * Write code to create a temporary file first * The code then reds from this file if it already exists --- user/src/lab0/helloworld.c | 37 +++++++++++++++++++++++++++++++++++-- 1 file changed, 35 insertions(+), 2 deletions(-) diff --git a/user/src/lab0/helloworld.c b/user/src/lab0/helloworld.c index f054b31..a49e796 100644 --- a/user/src/lab0/helloworld.c +++ b/user/src/lab0/helloworld.c @@ -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 +} -- 2.47.3