0

I want to read a file contents in C++ program which I have written inside a dll file. Right now I have hardcoded the path, but I want the path to be either dynamic or I should be able to use thru environment variable so I can either specify the path or the folder directly. I am using if stream in C++.Is there any way to do it

What I tried

if(const char* env_p = std::getenv("userdata"))
std::cout << "Your PATH is: " << env_p  <<'\n';
std::vector<std::string> v;
string line;
//ifstream Myfile("C:\\Program Files\\Folder1\\users.txt"); working as its has hardcoded path
ifstream Myfile("users.txt");--- not working
ifstream Myfile(%userdata%);--- not working

while(!Myfile.eof())
{
while(getline(Myfile,line))
v.push_back(line);
cout <<endl;
cout <<"User in the file"<<endl;
for(auto i:v)
cout << i<<endl<<endl;
Myfile.close();
}
  • You need this: [https://en.cppreference.com/w/cpp/utility/program/getenv](https://en.cppreference.com/w/cpp/utility/program/getenv) – drescherjm Feb 18 '21 at 13:06
  • I tried this already but it only displays the env varibale, I want the .txt file to be appended from the env path and use it in IFstream to read file . – Karthikeyan Sahadevan Feb 18 '21 at 13:14
  • That would be the way to get the environment variable. After you retrieve it you can put it in a std::string and append or whatever else you want to do with it. – drescherjm Feb 18 '21 at 13:15
  • Something like `std::string filename {env_p}; filename += "/users.txt";` – drescherjm Feb 18 '21 at 13:17
  • tried it in a different way after u said and it works, instead of a pointer I used normal string lol and it worked. Thx – Karthikeyan Sahadevan Feb 18 '21 at 13:23
  • [Why is iostream::eof inside a loop condition (i.e. `while (!stream.eof())`) considered wrong?](https://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-i-e-while-stream-eof-cons) – 463035818_is_not_a_number Feb 18 '21 at 13:36
  • In this case the outer `while(!Myfile.eof()){` loop should be removed. `while(getline(Myfile,line)) v.push_back(line);` reads the file correctly. I guess the OP meant to check if the file was open instead of the outer while loop – drescherjm Feb 18 '21 at 13:48
  • I got it friends, thx for your reply. – Karthikeyan Sahadevan Feb 18 '21 at 14:40

0 Answers0