简体   繁体   中英

write the integer value of a file descriptor to a file

Just testing out file descriptors. My aim is to open up a file stream with fopen and using fprintf write the file descriptors integer value back into the file to see what results im getting.

(I decided using fopen, fprintf etc) as it allowed me to write in variables, write() wouldn't allow it,

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

Issue i am facing is, if i write %d for the fprintf statement...i get a compiler error. If i write %p, I get the address in RAM.

Is it possible to get the absolute integer value...like "3"

FILE *fp;

is not a file descriptor, it's a file stream pointer and, as such, you need to treat it as a pointer.

A file descriptor is a small integer returned from one of the UNIXy calls like open or creat , while file pointers are sort of a level above that, assuming you're in an environment that even has descriptors.

In those environments, you can generally get at the underlying descriptor with something like:

int fd = fileno (fp);

The following complete program (under CygWin) shows this in action:

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

Compiling that with:

gcc -o testprog testprog.c

gives the output:

fp=0x800102a8, fd=3

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM