【问题标题】:write the integer value of a file descriptor to a file将文件描述符的整数值写入文件
【发布时间】:2014-12-15 00:42:54
【问题描述】:

只是测试文件描述符。我的目标是用 fopen 打开一个文件流,并使用 fprintf 将文件描述符整数值写回文件中,看看我得到了什么结果。

(我决定使用 fopen、fprintf 等)因为它允许我写入变量,而 write() 不允许,

#include <unistd.h>
#include <fcntl.h>
#include <stdio.h>

int main ()
{
  FILE *fp;

  fp = fopen("wow.txt", "w+");
  if (fp < 0)
    {
      printf("ERROR \n");
    }
  else
    {
      printf("we good \n");
    }

  fprintf(fp, "hi %p \n", fp);
}

我面临的问题是,如果我为 fprintf 语句编写 %d...我得到一个编译器错误。如果我写 %p,我会在 RAM 中获得地址。

是否可以得到绝对整数值...比如“3”

【问题讨论】:

  • 如果您打开一个文件,请在离开该功能之前将其关闭。并且您使用 fileno(fp) 从文件流(在 POSIX 上)获取文件描述符。

标签: c unix


【解决方案1】:
FILE *fp;

不是一个文件描述符,它是一个文件流指针,因此你需要把它当作一个指针来对待。

文件 descriptor 是从 UNIXy 调用之一返回的小整数,例如 opencreat,而文件 pointers 是高于该级别的,假设您处于一个甚至 具有 描述符的环境中。

在这些环境中,您通常可以通过以下方式获取底层描述符:

int fd = fileno (fp);

以下完整程序(在 CygWin 下)显示了这一点:

#include <stdio.h>

int main (void) {
    FILE *fp = fopen ("wow.txt", "w+");
    if (fp < 0) {
        printf ("ERROR\n");
        return 1;
    }

    fprintf (fp, "fp=%p, fd=%d\n", fp, fileno (fp));
    fclose (fp);

    return 0;
}

编译:

gcc -o testprog testprog.c

给出输出:

fp=0x800102a8, fd=3

【讨论】:

  • 好的,谢谢你澄清这个问题,只需阅读 fileno。你会推荐吗?
  • @Bobski,是的,如果您真的想从指针中知道文件描述符,我会的。而且,无需道歉,当我添加该建议时,您在编辑中发现了我 - 这种情况经常发生 :-)
  • 无论如何,干杯,再等几分钟,因为由于时间限制,我无法将您的答案标记为已解决。
猜你喜欢
  • 2012-03-24
  • 1970-01-01
  • 2019-06-20
  • 1970-01-01
  • 1970-01-01
  • 2012-04-08
  • 2019-05-22
相关资源
最近更新 更多