• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 827
  • Last Modified:

Converting int file descriptor to (file *) struct

Hi,

I'm really confused as to the mapping of integer file dscriptors, such as 0,1,2 (stdout and stderr) to (file *) structure on UNIX (specifically AIX), does anyone know how this is done?

Cheers

Andy
0
Ghostrider
Asked:
Ghostrider
  • 2
1 Solution
 
rdelfinoCommented:

You gotta use fdopen() to map a FILE* to an integer file descriptor.

try the example below:

--------------------------8<-------------------------

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

#include <errno.h>
#include <string.h>

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

int main(void)
{
  FILE *fd;

  int f;
 
  f = open("/tmp/test.txt", O_CREAT | O_WRONLY, 0644);
  if (f < 0)
  {
    fprintf(stderr, "(%d - %s) error opening /tmp/test.txt\n", \
      errno, \
      strerror(errno));
    return 1;
  }
 
  fd = fdopen(f, "w");
  if (!fd)
  {
    fprintf(stderr, "(%d - %s) error opening stream\n", \
      errno, \
      strerror(errno));
    return 2;
 
  }
 
  fprintf(fd, "Hello\n");
 
  fclose(fd);
 
  close(f);
  return 0;
}
0
 
GhostriderAuthor Commented:
kewl,

I actually wanted to map from the file struct to the integer index, but I've dealt with it, and at the expense of efficiency my code'll do!

I must remember fdopen!

Many thanks cheers

Andy
0
 
rdelfinoCommented:

Thanks

If you want to map a FILE* to an integer file descriptor
you gotta use fileno()

0

Featured Post

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now