简体   繁体   中英

How can I acces files with getenv() in c++ with using pipe in a bash?

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.

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM