Muhammad ammar usmani
Muhammad ammar usmani

Reputation: 89

What does this code mean "ofstream fout(getenv("OUTPUT_PATH"));"

I'm still new to cpp, and I will appericate if someone can help me to understand this line of code:

ofstream fout(getenv("OUTPUT_PATH"));

This code I saw almost every single Hacker Rank challange. What is the purpose of this code?

Upvotes: 4

Views: 11550

Answers (3)

R Sahu
R Sahu

Reputation: 206627

I say, when in doubt, simplify.

When something seems too complex and does not make sense at first glance, find ways to break it into smaller pieces that make sense to you.

ofstream fout(getenv("OUTPUT_PATH"));

can be broken into two pieces.

auto res = getenv("OUTPUT_PATH");
ofstream fout(res);

You can look up the documentation of getenv() to understand what the first line does. In your case, it returns the value of the environment variable OUTPUT_PATH. After the line is executed, res will be that value.

You can lookup the documentation for the constructors of ofstream to understand what the second line does. In your case, it constructs an ofstream object using the value of the environment variable OUTPUT_PATH.

After that line, you can use the fout object to write to the stream. The output will be available in the file defined by the environment variable OUTPUT_PATH.

The reason that Hacker Rank does this is because they have 100's or 1000's of users running the same pieces of code at the same time. To make sure each run uses a unique output file they set OUTPUT_PATH to a unique name before running the code. This will ensure that the output will be placed into a unique file. The wrapper code on Hacker Rank will then compare the output from your file against the expected output.

Upvotes: 22

shubham khantwal
shubham khantwal

Reputation: 33

it's an easy stuff. It is taking the output environment path and passing that to the object of output stream i.e fout.

Hope you remember ios_base -> ios -> ostream -> ofstream

As Per cppreference ,

std::ofstream

typedef basic_ofstream ofstream;

Output stream class to operate on files

std::getenv

Defined in header cstdlib

char* getenv( const char* env_var );

Searches the environment list provided by the host environment (the OS), for a string that matches the C string pointed to by env_var and returns a pointer to the C string that is associated with the matched environment list member.

check out your home path using:

#include <iostream>
#include <cstdlib>

int main()
{
    if(const char* env_p = std::getenv("PATH"))
        std::cout << "Your PATH is: " << env_p << '\n';
}

you are going to see all the paths you have set in your environment

environment has the location of the compiler or other executable stuff.

Upvotes: 0

APoster
APoster

Reputation: 93

It's creating an output file stream with the filename of whatever the environment variable "OUTPUT_PATH" is set to.

Upvotes: 3

Related Questions