Two ways of C language stream redirection

1. Use console commands (take windows as an example)

code:

#include<stdio.h>

int main()
{
	char c;
	while((c = getchar())!=EOF && c!='\n')
	{
		putchar(c);
	}
	return 0;
}

So how to use console redirection? Please see the console running screenshot:


Add > output stream name after the program to redirect the standard output stream to the stream of the output stream name, and add < input stream name to redirect the standard input stream to the stream of the input stream name


Screenshot of running results

Restrictions: Only standard input and output streams can be redirected, and only one file stream can be opened respectively.


2. Use freopen to redirect to open the library function

code:

#include<stdio.h>

int main(void)
{
	char c;
	if(freopen("stdin.txt","r",stdin) == NULL) //将标准输入流重定向至stdin.txt流 
	{
		fprintf(stderr,"打开文件失败!");
		exit(-1);
	}
	if(freopen("stdout.txt","w",stdout) == NULL)//标准输出流重定向至stdout.txt流
	{
		fprintf(stderr,"打开文件失败!");
		exit(-1);
	}
	while((c = getchar())!=EOF && c!='\n')
	{
		putchar(c);
	}
	return 0;	
}

Screenshot of running results

freopen is used to redirect input and output streams. This function can change the input and output environment without changing the original appearance of the code, but the stream should be reliable when used. Compared with console commands, it has better flexibility, and can specify the mode of opening the stream (such as "r" read-only mode);

C89 function declaration: FILE *freopen( const char *filename, const char *mode, FILE *stream );

C99函数声明:FILE *freopen(const char * restrict filename, const char * restrict mode, FILE * restrict stream);

Formal parameter description:

filename: The file name or file path that needs to be redirected to.
mode: A string representing the file access permissions. For example, "r" means "read-only access", "w" means "write-only access", and "a" means "append write".
stream: The file stream to be redirected.

Return value: If successful, returns the file pointer pointing to the output stream, otherwise returns NULL.

When the standard output stdout is redirected to the specified file, how to redirect it back to the original "default" output device (ie display)?
The reply of the C standard library is: not supported. There is no way to restore the original output stream.
Is there an implementation that depends on a specific platform? exist.
In the operating system, the command line console (that is, the keyboard or monitor) is regarded as a file. Since it is a file, it has a "file name". For historical reasons, the file name of the command line console file is "CON" in the DOS operating system and Windows operating system, and the file name in other operating systems (such as Unix, Linux, Mac OS X, Android, etc.) "/dev/tty".

Guess you like

Origin blog.csdn.net/g1093896295/article/details/79554448