如何将数据从 shell 中的标准输入传递到文件

How to pass data to a file from stdin in the shell

我的任务是编写一个 C 程序来说明使用系统调用的 mv 命令:

#include<stdio.h>
#include<errno.h>
#include<stdlib.h>
#include<unistd.h>
#include<sys/types.h>
#include<fcntl.h>
#define BUF_SIZE 8192
int main(){
int input_fd,output_fd;
ssize_t ret_in, ret_out; //number of bytes returned by read(), write()
char buffer[BUF_SIZE];
output_fd=open("sss", O_WRONLY | O_CREAT);
if(output_fd==-1){
        perror("open");
        return 3;
}
while((ret_in=read(stdin, buffer, BUF_SIZE))>0){
        ret_out=write (output_fd, buffer,(ssize_t) ret_in);
        if(ret_out!=ret_in){
                perror("write");
                return 4;
        }
}
close(output_fd);
input_fd=open("sss", O_RDONLY);
while((ret_in=read(input_fd,buffer, BUF_SIZE))>0)
        ret_out=write(stdout, buffer,(ssize_t) ret_in);
close(input_fd);
return 0;
}

如何 运行 shell 中的代码并从 stdin 向其传递文本? 请给我一个将数据从 shell

中的标准输入传递到文件的示例

首先修复您的代码,将 stdout 更改为 1(或 STDOUT_FILENO),将 stdin 更改为 0(或 STDIN_FILENO)。其他的是FILE *,属于fread和fwrite。任何体面的编译器都应该在那里警告你......

./MoveCommand < filename 是一种方法。

这会将 filename 的内容重定向到 stdin 并将其写入文件 "sss",之后读取该文件并将内容回显到 [=10] =].

所以你实际上是在做 cat filename,对某个固定文件有一个额外的副本。

./Movecommand 本身也是可能的。但是你必须自己输入(此时是 stdin),当你想发出完成信号时,请输入 Ctrl+D(Linux 或 Mac)或 Ctrl+ Z(Windows)。然后它会将你输入的所有内容回显给你,内容也在"sss".

当然,您也可以在管道中使用它,所以 ls -l | ./Movecommand 例如试试吧。