C语言的重定向输入和输出

通过不同的渠道重定向输入至文件和从文件输出

文件输入代码如下

#include <stdio.h>
//重复输入,指导文件结尾 
int main(void)
{
	int ch;
	while((ch=getchar()) != EOF){
		putchar(ch);
	}
	
	return 0;
 } 

上面文件是直接从键盘输入和屏幕显示

接下来重定向为输入至文件和从文件输出

1.重定向输入
在这里插入图片描述
在cmd命令符里执行方法,也输入程序名文件echo_eof.exe,然后输入重定向符号<,最后输入文本文件名。

文件里的内容为
在这里插入图片描述

2.重定向输出
在这里插入图片描述
cmd命令差不多,但是重定向符变成>

3.出现的问题
重定向输出的时候会有时乱码
在这里插入图片描述
等待解决

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
以下是实现输入重定向输出重定向的代码示例: ```c #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <fcntl.h> #include <string.h> #define MAX_CMD_LEN 256 int main() { char cmd[MAX_CMD_LEN]; char *args[MAX_CMD_LEN]; char *input_file, *output_file; int input_fd, output_fd; int i, j; while (1) { printf("myshell> "); fgets(cmd, MAX_CMD_LEN, stdin); // 读取命令行输入 if (feof(stdin)) { // 用户输入Ctrl+D,退出程序 printf("\n"); break; } // 解析命令行参数 args[0] = strtok(cmd, " \n"); i = 1; while ((args[i] = strtok(NULL, " \n")) != NULL) { i++; } args[i] = NULL; // 查找输入输出重定向符号 input_file = NULL; output_file = NULL; for (j = 0; j < i; j++) { if (strcmp(args[j], "<") == 0) { // 输入重定向符号 input_file = args[j+1]; args[j] = NULL; break; } if (strcmp(args[j], ">") == 0) { // 输出重定向符号 output_file = args[j+1]; args[j] = NULL; break; } } // 执行命令 pid_t pid = fork(); if (pid == -1) { perror("fork"); exit(1); } else if (pid == 0) { // 子进程 // 输入重定向 if (input_file != NULL) { input_fd = open(input_file, O_RDONLY); if (input_fd == -1) { perror("open input file"); exit(1); } if (dup2(input_fd, STDIN_FILENO) == -1) { perror("dup2 input"); exit(1); } close(input_fd); } // 输出重定向 if (output_file != NULL) { output_fd = open(output_file, O_WRONLY | O_CREAT | O_TRUNC, 0644); if (output_fd == -1) { perror("open output file"); exit(1); } if (dup2(output_fd, STDOUT_FILENO) == -1) { perror("dup2 output"); exit(1); } close(output_fd); } // 执行命令 execvp(args[0], args); perror(args[0]); exit(1); } else { // 父进程 waitpid(pid, NULL, 0); } } return 0; } ``` 在上述代码中,我们首先解析用户输入的命令行参数,查找输入输出重定向符号 `<` 和 `>`,并分别获取输入输出文件名。接着,在子进程中,我们使用 `open()` 函数打开输入输出文件,并使用 `dup2()` 函数将标准输入或标准输出重定向到文件描述符。最后,我们使用 `execvp()` 函数执行用户输入的命令。在父进程中,我们使用 `waitpid()` 函数等待子进程结束。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值