• Uncategorized

About c : Trying-to-implement-append-in-my-own-shell-Linux

Question Detail

I’m trying to implement append command in my own shell.
I succeeded to append to existing file but whenever I’m trying to append to file doesn’t exist it makes a file without any permission (not read and not write)

   if (append) {
        fd = open(outfile,'a'); 
        close (STDOUT_FILENO) ; 
        /* stdout is now appended */

What should I do to make a file with permissions

Question Answer

The open() system call doesn’t use a character constant to indicate ‘append’. Read the POSIX specification for open() — and look at O_APPEND etc. You need more flags than just O_APPEND, and you need three arguments to open() if you want to create the file if it doesn’t exist (O_CREAT), etc.

if (append)
    fd = open(outfile, O_CREAT|O_APPEND|O_WRONLY, 0644);
    if (fd < 0)
        …deal with error…

You can write 0644 as S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH but the octal is shorter and (after 30+ years practice) a lot easier to read. You can add write permissions for group (S_IWGRP) and others (S_IWOTH) if you like (0666 in octal), but unless you know you want group members and others to modify the files, it is safer to omit those — for all it goes against historical precedent. Users can and should set the shell umask value to 022 to prevent group and others from being able to write to files by default, but there’s no harm (IMO) in being secure without that.

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.