【问题标题】:C - Declare a file in function parametersC - 在函数参数中声明一个文件
【发布时间】:2016-11-29 09:23:20
【问题描述】:

所以这是我的问题:

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);
}

正在使用此代码检查打开命令是否有效,因为我刚刚开始学习如何使用它。

基本上这段代码工作得很好,但是我想在我的函数isopen的参数中声明我想直接打开的文件。

我看到其他一些帖子使用main的argc和argv,但我确实需要在我的函数isopen的参数中声明我的文件,而不是使用argc和argv。

有可能吗?

谢谢你的帮助,我很迷茫。

【问题讨论】:

  • 我建议您先阅读open() 的手册页并正确获取返回值,然后再使文件名更通用。
  • 类似isopen("somfilename.txt")??
  • "返回值...返回打开文件的文件描述符。返回值-1表示错误;"
  • 抱歉挑剔了,但是如果你没有从正确使用函数入手,那再往前走也没有意义。它在出错时返回 -1,并且您还没有捕获它。
  • 我一点也不知道你在说什么,我的代码几乎和你的一样,除了正确的测试,并从函数返回一个有用的值。祝你好运。

标签: c file parameters declare


【解决方案1】:

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

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

【讨论】:

  • 非常感谢!这正是我所需要的。抱歉,说明不清楚,我对英语有点挣扎,因为它不是我的母语。再次感谢对我的 if 条件的一点帮助!
  • 它实际上比无用更糟糕 - 它泄漏文件描述符,使其保持打开状态,并且进程只有有限数量的可用描述符。
【解决方案2】:
#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

【讨论】:

  • 欢迎,别忘了说“这个答案很有用”;)
  • 我没有足够的声望这样做,对不起!
  • @MarilouCassar :-) 不要写“他的答案很有用”,而是要支持它!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-01-15
  • 2021-05-30
  • 1970-01-01
  • 2021-05-16
  • 1970-01-01
相关资源
最近更新 更多