Linux每个进程启动默认会打开三个文件描述符0, 1, 2,分别代表"标准输入", “标准输出”, “标准出错”。自然地,可以在程序
中控制这三个文件描述符的开关闭。下面两个程序分别是“重定向标准输入到文件“和”标准输出到文件”
1. 重定向标准输入到文件
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
int main()
{
int fd;
close(STDIN_FILENO);
fd = open("./test1.txt", O_RDWR);
if ( fd < 0 )
{
perror("open file error");
return -1;
}
char string[32] = {0};
scanf("%s", string);
printf("%s\n", string);
close(fd);
return 0;
}
2. 重定向标准输出到文件
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
int main()
{
int fd;
close(STDOUT_FILENO);
fd = open("./test1.txt", O_RDWR | O_TRUNC);
if ( fd < 0 )
{
perror("open file error");
return -1;
}
char string[32] = {0};
scanf("%s", string);
write(fd, string, strlen(string));
close(fd);
return 0;
}
这里想说的一个问题是,在第二个例子中,刚开始使用的是printf,运行程序后文件始终得不到数据。后来使用fflush(stdout)语句才能刷新到文件。
这里 说明一个问题,printf标准IO函数是带缓冲的,而在PCB中,只有描述符1是与文件关联的。标准IO函数最终是会将数据写入到标准输出中。
而如果不发生重定向,标准输出(屏幕)是一个行缓冲设备,那么使用printf中的换行就能将数据写入到标准输出中。但是现在标准输出重定向到
文件了,文件是全缓冲的,将导致printf遇到\n也不能刷入文件中,故需要手动fflush