LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - General (https://www.linuxquestions.org/questions/linux-general-1/)
-   -   shell commands in c++ (https://www.linuxquestions.org/questions/linux-general-1/shell-commands-in-c-905297/)

_Chops_ 09-27-2011 05:10 PM

shell commands in c++
 
I am pretty new to programming and working with terminal. I am trying to create a program that will do a few things when i open terminal. this is the code i have so far


#include <unistd.h>

int main()
{
system("say -v zarvox bears beats battlestar galactica");
system("/Users/jarrodcoffin/prog/c/Basic/mine");
chdir("/Users/my_username/School/C++/template/template");

return 0;
}

the first two system functions work just fine. When I get to the "chdir()" it doesn't change the directory in the shell window that I am working in. Im sort of confused as to why it won't work. If someone is kind enough to explain why its not working, I would be extremely appreciative.

As a side note: this isn't for a school assignment, so I'm not cheating or anything.

MrCode 09-27-2011 05:32 PM

Why do you need to use a C program for this (you're not using any C++ features here; this is pure C)? Can't you just use .bashrc or .profile if you want to run these commands whenever you open a shell/terminal? (…or whatever gets parsed/run whenever you open a terminal on OS X; I've never done anything remotely "technical/geeky" on a Mac, so I wouldn't know for sure. :p)

Typically, when you want to run several shell commands in sequence, you use a shell script rather than a C/C++ program.

A suggested replacement:

Code:

#!/bin/bash

say -v zarvox bears beats battlestar galactica
/Users/jarrodcoffin/prog/c/Basic/mine
cd /Users/my_username/School/C++/template/template

…have this called from .bashrc or .profile or whatever it is on OS X, or just put the commands in one of those directly (without the shebang line at the top).

I apologize if you already know this and are simply trying to deliberately run shell commands from a C program for practice. :p

millgates 09-27-2011 05:35 PM

Quote:

Originally Posted by _Chops_ (Post 4483838)
When I get to the "chdir()" it doesn't change the directory in the shell window that I am working in. Im sort of confused as to why it won't work. If someone is kind enough to explain why its not working, I would be extremely appreciative.

chdir() only changes the working directory for the C program (you can see that by running pwd from within the C program), not for the shell environment you run the program from.

_Chops_ 09-27-2011 07:17 PM

thank you mr code and mill gates. So I guess what I'm looking for is something that will change the environment I'm running the program in. It doesn't necessarily have to be in "C". the way i was doing it before bugged me so i wanted a different way. thanks for the suggestions mr. code. I'll try that.


All times are GMT -5. The time now is 07:40 PM.