ITguy
ITguy

Reputation: 888

Can output from c command system() go into a file instead of displaying on the console?

Can output from c command system() go into a file instead of displaying on the console?

Output of the

  system ("echo 123")

command that I use in c and then run it on Linux. It prints

123

on the screen. But if I write:

  system ("echo 123 >null")

it says cannot create file null. Can somebody please tell me how I can call this

system("echo 123")

without it displaying anything on the terminal. Any help is greatly appreciated.

The error message I recieve when I write

system("echo 123 > null")

Output

null: cannot create 

I am sorry this post is growing longer. OK! The problem is I have my own application that I am calling using System command. This application is in myapp/bin, the code that I am running is in another Folder c_prog/mycode.x .

Now I have full rights in myapp/bin and also in c_prog/mycode.x but I am getting the same problem

Upvotes: 0

Views: 135

Answers (3)

Ahmad Raza
Ahmad Raza

Reputation: 5

It is possible as well easy. Just use the pipe operator to redirect one command's output to input of second command(you want 'cat'). Like following

system("echo 'Hello World' | cat ./file.txt");

Here command echo give output "Hello World", which is redirected using |(pipe) operator and then this be the input of cat command, which writes it to file ./file.txt. See cat command before use.

Upvotes: 0

ITguy
ITguy

Reputation: 888

I figured the problem out... and yeah I was making a silly mistake. In the folder I was trying to create this null file I already had a null named Folder.

Silly me! That is why it was not creating a file of that same name... however Linux could have given me a more appropriate warning.

Upvotes: 0

LBes
LBes

Reputation: 3456

Check your rights on the working directory. If you don't have write-access surely you cannot create the file in the working directory in which case a sudo chmod 755 your_directory will help to give read and write rights.

Words of cautions. You might to check why you cannot write in the directory. There may be a very good reason for that. If the directory is not yours you may want to be careful before messing with it. One suggestion would also be then to change your working directory to a directory you created yourself.

Upvotes: 1

Related Questions