-1

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.

2 Answers2

2

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.

Jabberwocky
  • 48,281
  • 17
  • 65
  • 115
  • Thank you so much ! This is exactly what I needed. Sorry for unclear instructions, I struggle a bit with english as it's not my mother language. And thanks again for the little help with my if conditions ! – Marilou Cassar Nov 29 '16 at 09:51
  • It's actually worse than useless - it leaks the file descriptor, leaving it open, and a process only has a limited number of available descriptors. – Andrew Henle Nov 29 '16 at 10:47
0
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

int isOpen(char *filename)
{
   return open(filename, O_RDONLY);
}

int main() 
{
    printf("%d\n", isOpen("/home/viswesn/file1.txt"));
    printf("%d\n", isOpen("file2.txt"));
    return 0;
}

Output

    viswesn@viswesn:~$ cat /home/viswesn/file1.txt
    hello
    viswesn@viswesn:~$
    viswesn@viswesn:~$ cat /home/viswesn/file2.txt
    cat: /home/viswesn/file2.txt: No such file or directory
    viswesn@viswesn:~$
    viswesn@viswesn:~$ ./a.out
    3     <---------- File exist and it give file descriptor number '3'
                      STDIN-0, STDOUT-1, STDERR-2 are reserved and 
                      next file opened will start with 3 and it keeps going
    -1    <---------  File not found; so open gives -1 as error
Viswesn
  • 4,674
  • 2
  • 28
  • 45