user6200539
user6200539

Reputation: 3

Error in C code. Will show up "No file"

I have problem with this code. When I gonna run it it'll show me "No File"

#include <string.h>
#include <stdio.h>
main (argc, argv)
char *argv[];
{
    int fd;
    extern int errno;
    if (argc < 2) {
            fprintf (stderr, "No file\n");
            exit(1);
    }

    if ((fd = creat(argv[1], 0777))< 0){
            fprintf(stderr,"Cannot create file %s\n", argv[1]);
    exit(1);
}

switch (fork()) {
    case -1:
            fprintf(stderr, "Fork error\n");
            exit(1);
    case 0:
            close(1);
            dup(fd);
            close(fd);

            execl("/bin/ls", "ls", NULL);
            perror("Exec");
            break;
    default:
            wait(0);
            close(fd);


}
exit(0);
}

and will put out "warning: incompatible implicit declaration of built-in function 'exit'" - for all 5 exit.

Upvotes: 0

Views: 400

Answers (1)

Jabberwocky
Jabberwocky

Reputation: 50912

You are facing two distinct problems:

When you run the program it displays "No File"

This is because when you invoke the program, you aren't supplying a file name on the commande line, therefore argc is 1, hence the message.

You get the warning: incompatible implicit declaration of built-in function 'exit' when you compile

This is because you didn't include <stdlib.h> which contains the declaration of exit.

You should also get more warnings due to the lack of including <unistd.h>, <fcntl.h> and <wait.h>.


Side note

You declare extern int errno; (without using btw). Instead of doing this, you should include .


Side note 2

You should consider "implicit declaration" warnings as errors.

Upvotes: 2

Related Questions