Stranger Stranger - 4 months ago 6x
Bash Question

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

My task is to write a C program to illustrate the mv command using system Calls:

#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);
return 3;
while((ret_in=read(stdin, buffer, BUF_SIZE))>0){
ret_out=write (output_fd, buffer,(ssize_t) ret_in);
return 4;
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);
return 0;

How to run that code in the shell and pass it text from stdin?
Please, give me exapmle of passing data to a file from stdin in the shell


First fix your code and change stdout to 1 (or STDOUT_FILENO) and stdin to 0 (or STDIN_FILENO). The others are FILE * and belong to fread and fwrite. Any decent compiler should have warned you there...

./MoveCommand < filename is one way.

This will redirect the contents of filename to stdin and it will be written to the file "sss", after which this file is read and the contents echoed to stdout.

So you're doing cat filename essentially, with an extra copy to some fixed file.

./Movecommand by itself is also possible. But then you have to type input yourself (this is stdin at that point) and when you want to signal you're done rnter Ctrl+D (Linux or Mac) or Ctrl+Z (Windows). Then it will echo everything you typed back to you, and the contents are also in "sss".

You can also use it in a pipe, of course, so ls -l | ./Movecommand e.g. Try it.