C - Declare a file in function parameters

时间:2016-11-29 09:23:20

标签: c file parameters declare

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 个答案:

答案 0 :(得分:2)

你的问题不清楚,但也许你想要这个:

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);
}
顺便说一句,这里的isopen函数仍然没用,因为它只是打开文件并丢弃fd

答案 1 :(得分: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;
}

输出

    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