【问题标题】:C open files : number of opened file [closed]C打开文件:打开文件的数量[关闭]
【发布时间】:2012-10-01 05:29:33
【问题描述】:

全部,

有什么办法可以获取我的程序c中打开文件的数量

问题是:使用 lex 和 yacc 解析文件列表时

yyin 收到当前流的 fopen,最后(yywrap)我使用 fclose 关闭 yyin:所以通常打开文件的数量等于零。 对于某些示例,当我调用 fopen(许多已打开的文件)时,我会收到此错误异常

所以我的问题是如何从系统命令中获取打开文件的数量以调试此问题。

感谢帮助

【问题讨论】:

  • 发布一些代码可能会有所帮助。
  • 我解决了我的问题:有一个名为 openfiles 的系统函数,它为您的进程描述了打开文件的列表。重复包含的不需要的 fopen 导致此问题全部考虑

标签: c iostream yacc lex


【解决方案1】:

如果你只使用fopenfclose,那么你正在寻找的东西(我认为)可能会通过这样的技巧来实现:

#include <stdio.h>

unsigned int open_files = 0;

FILE *fopen_counting(const char *path, const char *mode)
{
    FILE *v;
    if((v = fopen(path,mode)) != NULL) ++open_files;
    return v;
}

int fclose_counting(FILE *fp)
{
    int v;
    if((v = fclose(fp)) != EOF) --open_files;
    return v;
}

#define fopen(x,y) fopen_counting(x,y)
#define fclose(x) fclose_counting(x)

当然,像这样的 sn-p 只会影响您可以控制的代码:在调用 fopenfclose 之前,它必须是 #included - 否则,原来的将调用函数而不是您的替换。

当涉及到返回当前打开文件描述符数量的系统函数时,很遗憾我不知道这样的事情。但是,是什么阻止了您在调试器下运行应用程序、在fopen 上设置断点以及仅使用操作系统工具检查该数字?在 Linux 上,进程中打开的文件描述符的数量等于目录 /proc/$PID/fd 中的条目数 - 通过这样做,您甚至可以知道哪个实际文件分配给了哪个文件描述符。

【讨论】:

    【解决方案2】:

    您可以使用整数,将其设置为等于0,并在每次使用fopen 时递增,每次使用fclose 时递减。

    file *fp;                  
    int files_opened = 0;      //number of open files
    
    if(!(fp = fopen("file.txt", "r"))) //open file
    {
                               //could not open file
    }
    else files_opened++;       //we opened a file so increment files_opened
    printf("\n%d files are currently open.", files_opened); //display how many files currently open
    if(!(fclose(fp) != EOF)))  //close file
    {
        //could not close file
    }
    else files_opened--;       //we closed a file so decrement files_opened
    printf("\n%d files are currently open.", files_opened); //display how many files currently open
    

    【讨论】:

    • thnks 看起来很简单,我问我是否可以像这个函数一样从系统获取这些信息,它在打开文件时返回错误 strerror(errno)
    • 我更新了我的答案,你将不得不自己跟踪它。我就是这样做的。但你的情况可能不同。
    • 我也为你更新了我的问题,它并不像你想象的那么明显。
    • 我再次更新了我的答案。如果每次调用fclosefopen 时增加/减少files_opened,那么files_opened 将等于您当前打开的文件数量。 printf("\n%d files are currently open.", files_opened); 会将该数字输出到控制台。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-26
    • 1970-01-01
    • 2010-12-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多