Convert file descriptor to file pointer | Convert file pointer to file descriptor in Linux by C programming

By -

 If you all ready know the difference between file descriptor and file pointer then good otherwise please read this post

Whats is difference between file descriptor and file pointer?

 

 

File descriptor to file pointer :

for converting file descriptor to file pointer in linux fdopen() function is used

#include <stdio.h
FILE *fdopen(int fildes, const char *mode);

fildes is file descriptor

mode is the character value which indicate the mode of file operation (same as we use in fopen() function)

Example :

#include <stdio.h>
#include <fcntl.h>
 
int main(){
int fd;
FILE *fp;
fd = open("shareprogrammingtips.txt",O_WRONLY | O_CREAT | O_TRUNC);
if(fd<0)
{
   printf("open call fail");
   return -1;
}
 
fp=fdopen(fd,"w");
fprintf(fp,"we got file pointer fp bu using File descriptor fd");
fclose(fp);
close(fd);
return 0;
}


 File pointer to file descriptor:

for converting file pointer  to file descriptor in linux fdopen() function is used

#include <stdio.h>

int fileno(FILE *stream);

stream is file pointer

Example:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
 
int main(){
int fd;
FILE *fp;
int size;
char *buffer;
fp = fopen("shareprogrammingtips.txt","r");
if(fp==NULL)
{
   printf("open call fail");
   return -1;
}
/* Logic for calculating size of file*/
fseek(fp,0,SEEK_END);
size = ftell(fp);
fseek(fp,0,0);
 
if((buffer=malloc(size)) == NULL)
{
printf("Malloc fail");
return -1;
}
 
fd=fileno(fp);
read(fd, (void*)buffer, size);
printf("size is %d Buffer is %s ",size,buffer);
fclose(fp);
close(fd);
return 0;
}

hey I am an Artist who love to write code...! Well I am an EC graduate From Ganpat University and now i am working as Embedded software engineer in one private firm.. find me at here Jeegar Patel

1 Comment to Convert file descriptor to file pointer | Convert file pointer to file descriptor in Linux by C programming

Leave a Reply

Your email address will not be published. Required fields are marked *

CAPTCHA Image

*