View Full Version: using linux shell command in C++

C++ Learning Community > C++ for Linux > using linux shell command in C++


Title: using linux shell command in C++


huno - April 14, 2005 03:55 PM (GMT)
hi people
can i use linux shell command into C++ programs ?
To copy files from place to other.. using "cp ¨ command ..

thanks

C-Man - April 14, 2005 04:02 PM (GMT)
system ( "command" )

C00L - April 16, 2005 03:42 PM (GMT)
QUOTE (C-Man @ Apr 14 2005, 04:02 PM)
system ( "command" )

hmm... that has never worked for me, i think the system command might be a windows/dos thing

i get errors like
test.cpp:4: implicit declaration of function `int system(...)'

Nintendofreak88 - April 16, 2005 03:50 PM (GMT)
Well did you pass a string to it? That could be why. Also you are probably compiling with gcc and not g++ since i think only C allows you to implicitly declare functions.

KTC - April 17, 2005 12:36 AM (GMT)
Erm
CODE
int system( const char *command );
is a standard library function that's available under both C and C++. It's declared in <stdio.h> and corresponding C++'s <cstdlib>.

IllegalEnzyme - May 17, 2005 09:13 AM (GMT)
it works for me when i #include <iostream>

KTC - May 17, 2005 11:56 PM (GMT)
QUOTE (IllegalEnzyme @ May 17 2005, 10:13 AM)
it works for me when i #include <iostream>

FFS, how many time do I have to say it. <_<

Anyway, the reason is, the library implementation you're using happens to include <cstdlib> indirectly when you include <iostream>. This is fine. However, there is absolutly no guarantee that this is the case. A library implementation doesn't have to implement it that way. A new version of that library could do it differently, a different library implementation could do it differently. Just don't assume it does get included. If you want to use a function declare in a particular library header, include that library header.

Incubator - May 18, 2005 11:25 AM (GMT)
Also please note that it is very bad practice to use commands in programs like that.
You force the user to have that specific command.

It is always better and faster to use native C++ functions

I had that same thing with removing a dir, at first I was thinking of using system("rm -R ...")
but there is an rmdir() function wich I found later.

to copy a file its even easier, use an ifstream and ofstream :)

also check out the GNU C library for more linux specific functions


If you really still want to use OS-specific commands, i suggest shellscripting

CODE

#!/bin/bash

ls -l $HOME
mkdir $HOME/bin
cp /usr/bin/ld $HOME/bin
echo "Copied ld over to $HOME/bin" # wich prints on my pc "Copied over ld to /home/incubator/bin"


in windows:
CODE

dir %USERPROFILE%
copy somefile %USERPROFILE%; copies file to your Documents and settings user dir

IllegalEnzyme - May 19, 2005 01:29 PM (GMT)
yeah, ok, i mainly use them in progs just working on my comp so that i know that i have the command.




Hosted for free by InvisionFree