This blog is under construction

Friday, 6 April 2012

tmpfile example in C

Header file:
     stdio.h

Synopsis:
     FILE *tmpfile(void);

Description:
     Creates a temporary file in "wb+" mode and that file will be automatically deleted when the programs execution gets complete.  Returns stream on success, or NULL on failure.


tmpfile function C example: (How to get file name from file descriptor?)


  #include<stdio.h>
  #include<string.h>
  #include<unistd.h>
  int main() {
        FILE *fp;
        char str[100], buffer[100], length=50;
        int fd;
        fp = tmpfile();
        if(fp == NULL) {
                printf("Error in creating temporary file\n");
                return;
        }
        fprintf(fp, "Hello world");
        rewind(fp);
        fd = fileno(fp);
        fgets(str, 100, fp);
        printf("%s", str);
        sprintf(str, "cat /proc/%d/fd/%d", getpid(), fd);
        printf("\n\nContents present in the file:\n");

        /* 
         * executes the command "cat /prop/1734/fd/3"
         * 1734 - process id & 3- file descriptor (for eg.)
         */
        system(str);

        /* mapping file descriptor to file name */
        sprintf(str, "/proc/self/fd/%d", fd);
        readlink(str, buffer, length);
        printf("\nFilename:\n");
        printf("\n%s\n", buffer);
        fclose(fp);
        return 0;
  }



  Output:
  jp@jp-VirtualBox:~/cpgms/exp$ ./a.out
  Hello world

  Contents present in the file:
  Hello world
  Filename:
  /tmp/tmpfbar0kt (deleted)



No comments:

Post a Comment