#JV1 : Stuck on redirecting stdout

I have been stuck on this error for too long.
My approach is as follows. For built-in commands, I check if redirection is present or not and create the redirect file if it doesn’t exist.
But the problem is coming in external commands like ls
Here, my approach is to first find the relative path to the current directory, resolve it, and then normalize it to obtain the final path. I then check if its parent directories are present; if not, I create them. Then redirect to the file.
But it’s not working. Can you help me see where I have gone wrong.

Here is my github link : GitHub - Molik2801/codecrafters-shell-java

Hi, thanks for your post!

I’m currently out of the office for the holidays and will be back on January 5. I’ll get back to you as soon as possible once I return.

1 Like

You are concatenating this “user.dir” with the redirect, so you end up with a non-sense path. If you are in /a/b and the redirect is >/x/y/z you use Path.of to get /a/b/x/y/z.

2 Likes

But if I get a relative path for redirection, then what should I do?
I was confused in it thats why i concatenated with currentdirectory.

Well if you get a relative path then you should use that relatively, and if you don’t you should the absolute. On POSIX/Linux you could possible try and see if there is a leading /. But I don’t even bother and instead delegate it to opensystem function:

```c
int flags = O_RDWR | O_CREAT;
if (redirect->flags & CMD_REDIRECT_APPEND) {
flags |= O_APPEND;
} else {
flags |= O_TRUNC;
}
return open(redirect->fileTarget, flags);
```

2 Likes

Ah cool.
Thanks, but I found my error, and it was a silly one.
When I parsed my redirection string, there were two errors: first, that it started with an extra space, and second, when passed with quotes, it also included quotes, causing a problem in resolving the path.

The logic of resolving with the current directory is fine. only thing wrong was the way i was resolving that was using string, instead have to do with Path object only.

1 Like

Glad you got it working.

Besides the parsing error, the logic to get the redirect path when I looked was: Path file = Path.of(curDir.toString() , redir).normalize(); and when I tried Path.of(“/a/b”, “/x/y”) I got /a/b/x/y.You changed that to Path file = curDir.resolve(redir).normalize();.

Beware though Path.resolve(path) says: Where the given path has a root component then resolution is highly implementation dependent and therefore unspecified. Nvm, they fixed that somewhere between Java 8 and 21: If the other parameter is an absolute path then this method trivially returns other

2 Likes

yup , earlier i resolved wrong :stuck_out_tongue:
Thanks for help.

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.