Hay Asa
Hay Asa

Reputation: 9

Trying to implement append in my own shell Linux

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'); 
        lseek(fd,0,SEEK_END);
        close (STDOUT_FILENO) ; 
        dup(fd); 
        close(fd); 
        /* stdout is now appended */
    } 

What should I do to make a file with permissions ?

Upvotes: 1

Views: 180

Answers (1)

Jonathan Leffler
Jonathan Leffler

Reputation: 753930

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.

Upvotes: 1

Related Questions