Life Whiz
Life Whiz

Reputation: 58

Undefined Reference to 'main' when code is compiled

I created a C program which would create a directory and file.

I have tried to debug the error, but it didn't work

#include <dirent.h>
#include <errno.h>
#include<stdio.h> 
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <stdlib.h>

create_dir(char* outputdir,char* str_outpath,char* value){

DIR* dir = opendir(outputdir);
FILE *f;

if (dir) {
    /* Directory exists. */
    closedir(dir);
} else if (ENOENT == errno) {
    /* Directory does not exist. */
    mkdir(outputdir, 0700);
    closedir(dir);
    printf("Successfully created the directory %s ", outputdir);

} else {
    printf("Creation of the directory %s failed",outputdir);
    /* opendir() failed for some other reason. */

}

f = fopen(str_outpath, "a");
fprintf(f,"%s",value);
fclose(f);

}

I want it to create a file and a directory successfully

Upvotes: 0

Views: 418

Answers (2)

tbejos
tbejos

Reputation: 524

In C under most cases you need to have a main function. So in order to run your code you'll need to have something like this (assuming that you want to pass in the parameters from the command-line) underneath that function:

int main(int argc, char *argv[]) {

    if (argc < 4) {
        printf("Proper Usage is ./program otputdir str_outpath value\n");
        return -1;
    }

    char *outputdir = argv[1];
    char *str_outpath = argv[2];
    char *value = argv[3];

    create_dir(outputdir, str_outpath, value);
    return 0;
}

EDIT: fixed an issue with not checking argc

Upvotes: 3

Tofu
Tofu

Reputation: 3613

As others have mentioned. You do not have a main function. Also your create_dir function is missing a type. I'll assume it's void since you are not returning anything. This should compile.

#include <dirent.h>
#include <errno.h>
#include<stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <stdlib.h>

void create_dir(char* outputdir,char* str_outpath,char* value){

    DIR* dir = opendir(outputdir);
    FILE *f;

    if (dir) {
        /* Directory exists. */
        closedir(dir);
    } else if (ENOENT == errno) {
        /* Directory does not exist. */
        mkdir(outputdir, 0700);
        closedir(dir);
        printf("Successfully created the directory %s ", outputdir);

    } else {
        printf("Creation of the directory %s failed",outputdir);
        /* opendir() failed for some other reason. */

    }

    f = fopen(str_outpath, "a");
    fprintf(f,"%s",value);
    fclose(f);
}

int main(){
    char directory[] = "/users/me/documents/testdir";
    char filepath[] = "testfile";
    char data[] = "hello world";
    create_dir(directory,filepath,data);
    return 0;
}

I did not execute the code to check whether it works. I merely copied and pasted yours and called the function.

Upvotes: 5

Related Questions