Question

I looked around on this site and others and couldn't find an answer to my likely elementary issue. I'm on AIX at work and am trying to learn system programming. Stevens' book is a little much at this point and I haven't found a good "practical" systems programming book.

That said, I'm trying to write a program in C that does basically what a script (I've called "cure") wrote a while back does. Here is the very simple script (at this stage, I'm not changing user/group/others permissions to full -- I thought I'd hit that hurdle next; suggestions on the easiest way to do that are welcomed though):

## cure: changes permissions on all arguments to 777

sudo chmod 777 $*

Now here is my cure.c code:

#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>

int main(int argc, char **argv)
{
        int i, *fd;
        //FILE *fd;
        if(argc == 1)
                printf("Usage: cure file1 file2 ...\n");

        for( i = 1 ; i < argc ; i++ )
        {
                fd = fopen(argv[i], "rw");
                if(!fd)
                        printf("Cannot open %s\n", argv[i]);
                fchmod( fd, S_IXUSR);
                close(fd);
        }
        exit(0);
}

I've done some tweaking trying to get the program to work. As it stands now, here are the warning messages that gcc prints:

cure.c: In function 'main': cure.c:15:6: warning: assignment from incompatible pointer type [enabled by default] cure.c:18:3: warning: passing argument 1 of 'fchmod' makes integer from pointer without a cast [enabled by default] /usr/include/sys/stat.h:330:13: note: expected 'int' but argument is of type 'int *' cure.c:19:3: warning: passing argument 1 of 'close' makes integer from pointer without a cast [enabled by default] /usr/include/unistd.h:142:12: note: expected 'int' but argument is of type 'int *'

If I change my fd variable to a non-pointing int, this is what I get:

cure.c: In function 'main': cure.c:15:6: warning: assignment makes integer from pointer without a cast [enabled by default]

Again, I realize this is pretty elementary, so there are some concepts that I'm not getting yet.

Thanks

Was it helpful?

Solution

fopen returns a FILE *, which is a C stream abstraction. You can use it like so:

FILE *f = fopen(...);

open returns an integer file descriptor, and you can use it like so:

int fd = open(...);

they're different functions, and different types, and you're mixing them up.

Since fchmod takes an integer file descriptor, you want to use the basic open/close/integer file descriptor family of functions, not the fopen/fclose/FILE* family of functions.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top