I have the following code example (in windows):

int fd = _dup(fileno(stdout));
freopen("tmp","w",stdout);

printf("1111");
close(stdout);

char buf[100];

FILE *fp;   
fp = fopen("tmp","r");//in this line fd turns to be 0
if(NULL == fp) return -1;
fgets(buf,100 , fp) != NULL );
fclose(fp);

I need the value of fd for the futher use.How can I read from file without loosing the fd value?

fp = fopen("tmp","r");//in this line fd turns to be 0

I didn't see any fd, there.

freopen("tmp","w",stdout);

Wouldn't it be a good idea to save it's return value(i.e. file handle) somewhere else to use it later.

close(stdout);

'Close' takes an integer representing filehandle to the opened file.

fgets(buf,100 , fp) != NULL );

Aren't you mising something here?

Edited 5 Years Ago by D33wakar: n/a

I didn't see any fd, there.

Wouldn't it be a good idea to save it's return value(i.e. file handle) somewhere else to use it later.

'Close' takes an integer representing filehandle to the opened file.

Aren't you mising something here?

There was a typo in code  
int fd = _dup(fileno(stdout));
freopen("tmp","w",stdout);

printf("1111");
close(stdout);

char buf[100];

FILE *fp;   
fp = fopen("tmp","r");//in this line fd turns to be 0
if(NULL == fp) return -1;
if(fgets(buf,100 , fp) != NULL );
else return -1
fclose(fp);

Edited 5 Years Ago by yakovm: n/a

I need the value of fd for the futher use.How can I read from file without loosing the fd value?

I haven't understood what you want exactly, but the code below might help you.

#include <stdio.h>
#include <io.h>

int main(void){
	FILE* fp;
	int fd;

	if(fp=freopen("test.txt","w",stdout)){//opened "test.txt" as the 'stdout'
	   puts("Hello, world!");//prints to the file "test.txt"

	   if((fd=_dup(fileno(fp)))!=-1){//fd is another handle to "test.txt"

		   close(fd);//correct form of 'close'
		}
		fclose(fp);
	}
	return 0;
}
This article has been dead for over six months. Start a new discussion instead.