0

I have to write a c++ program which "counts the number of lines, words and the number of bytes from a text file", all of which must be in a new line.

I have to use the wc command in my c++ program. I have managed to get the number of lines:

char *envp[] = {NULL};
char *command[] = {"wc", "-l", filename.c_str(), NULL};
execve("/usr/bin/wc", command, envp);

After the above statements, I have one which replaces "-l" with "-w" and so forth. But my program ends immediately after the first execve() statement.

How do I get all my statements to execute even after the execve() statement?

N.B: This will be my first time running system commands using a c++ program.

Thank you in advance.

Mukesh A
  • 323
  • 1
  • 4
  • 13
Ofentse
  • 3
  • 2
  • `char *command[] = {"wc", "-l", filename.c_str(), NULL};` is not a valid initialization, "wc" could be a `char const *`, but not `char *` – user7860670 Aug 11 '18 at 15:01
  • I've performed a type cast within the array (char *)"wc". I decided to leave out all my type casts from the code because they're not what I'm having trouble with – Ofentse Aug 11 '18 at 15:06
  • 1
    That type cast is not valid either because strings command pointers point to must be modifiable. – user7860670 Aug 11 '18 at 15:19
  • Read [Advanced Linux Programming](http://www.makelinux.net/alp/) -or something newer- then [syscalls(2)](http://man7.org/linux/man-pages/man2/syscalls.2.html) and related `man` pages. Read also [*Operating Systems: Three Easy Pieces*](http://pages.cs.wisc.edu/~remzi/OSTEP/) for a good overview about OSes. – Basile Starynkevitch Aug 11 '18 at 18:15
  • thank you for the references. – Ofentse Aug 12 '18 at 19:31

1 Answers1

2

execve replaces current executable image with a specified one and therefore never returns upon success. If you want to continue executing main program then you will need to fork first. Or use something as dull as system function.

user7860670
  • 35,849
  • 4
  • 58
  • 84
  • Thank you. As I mentioned I'm relatively new to this, I'll do some research about fork(). Thank you. – Ofentse Aug 11 '18 at 15:36