0

I want to implement a function for MapReduce framework so my task is to create a mapper that concatenate text files.

Here is my bash script;

 for i in text1.txt text2.txt text3.txt
     do
         cat $i | ./myfunction
     done

And myfunction() will read the input files , line by line and the variable will be read with function getenv(). I tried with fopen(argv[1],"r") it gives me Segmentation fault and with popen() I get permission denied.

My code in C++:

 char *myenv;
 myenv = getenv("PWD");
 FILE *fileIN = popen(myenv , "r");

I don't know what exactly cat $i | ./myfunction does.Does it read "i" like an argument ? if yes, I get fileIN == NULL when I use fopen.

  • Can you try to elaborate on what your intention is, and maybe share the C++ code? – Enlico Nov 20 '19 at 23:02
  • I hope that it seems better now – Carlos Ermani Nov 20 '19 at 23:20
  • Piping will make data available on stdin. You should read a line from stdin as if you were trying to read user input. – that other guy Nov 20 '19 at 23:28
  • @thatotherguy. Yes I thought so but why do I need getenv() then? Do you have an opinion for that ? – Carlos Ermani Nov 20 '19 at 23:40
  • 1
    I don't know why you would need it. Nothing about the problem description suggests that `getenv` should be involved. – that other guy Nov 21 '19 at 00:06
  • I guess you want to extract variable names and values by reading `*.txt` files. If you can provide some lines of them and describe what you want to do with them, we could be your help. I suppose `getenv` has nothing to do with it. – tshiono Nov 21 '19 at 02:13

1 Answers1

1

You are making a confusion here. getenv allows you to get environment variables, like PWD, which is just the path to your home directory.

Here, the pipe adds the output of the echo command to the args given to your executable. To get these args you should write your C++ code like this:

int main(int argc, char *argv[]) {
    //do whatever you want with argv[1]
    return 0;
}

Edit: if you want to get the name of the file in your C++ code, you should use echo instead of cat.

  • I am not allow to change anything in bash. So in this case I can not use argv. I read line from stdin but how can I get that which file are piping I have to get filename and index for every words – Carlos Ermani Nov 21 '19 at 10:37