Marilou Cassar Marilou Cassar - 8 days ago 6
C Question

C - Declare a file in function parameters

so here is my problem :

int isopen()
{
int fd;

fd = open("myfile", O_RDONLY);
if (fd == 0)
printf("file opening error");
if (fd > 0)
printf("file opening success");
return(0);
}

int main(void)
{
isopen();
return(0);
}


Is use this code to check if this the open command worked, as i'm just starting to lurn how to use it.

Basically this code is working just fine, but I would like to declare the file I would like to open directly in the parameters of my function isopen.

I saw some other posts using main's argc and argv, but I really need to declare my file in the parameters of my function isopen, not using argc & argv.

Is it even possible ?

Thank you for your help, I'm quite lost here.

Answer

Your question is unclear, but maybe you want this:

int isopen(const char *filename)
{
    int fd;

    fd = open(filename, O_RDONLY);
    if (fd < 0)                           //BTW <<<<<<<<<<<<  fd < 0 here !!
        printf("file opening error"); 
    else                                  // else here
       printf("file opening success");

    return(0);
}


int main(void)
{
   isopen("myfile");
    return(0);
}

BTW, the isopen function as it stands here is still pretty useless as it just opens the file and throwing away fd.