appending "../xx.txt" to the relative path does work in C++ - c++

I read some topics about relative path, but I've been wandering around them for hours without answer.
The code is like this:
std::string path = "./Debug/";
path.append("../hi.txt/");
std::ifstream inFile(path);
std::string str;
if (inFile.is_open())
{
inFile >> str;
std::cout << str << std::endl;
}
else
{
std::cout << "open failed" << std::endl;
}
This code will output:"open failed".
Any help would be appreciated.

When you put a / at the end of a path, it tells the system to execute it as a directory (i.e. list its contents). Since hi.txt is not a directory, you can't execute it as a directory and therefore it fails (assuming of course you didn't name a directory hi.txt).
To fix it: remove the /:
std::string path = "./Debug/" ;
path.append("../hi.txt") ;

Related

Finding a string inside all subdirectories

I try to code a program that behaves like grep -r function. So far I can list all the subdirectories and folders inside of them recursively but what i need to do is to find a string inside all of these files and record them in a .log file. I am building with CMake on Ubuntu. The program compiles fine but probably I have something wrong with this function.(it basically saves the values found in a log file)
It's supposed to put inside the log file the following->
Directory:(line number):(the full line)
After the changes, the function works fine, I can see the directories and the line number of the searched word. The problem now is that I cannot see the line in the .log file, it shows in binary and not as a string. Do anyone know the reason ?
void showing_all_files(std::string path, std::string search)
{
std::ofstream log_file;
log_file.open("grep_ex.log");
for (const auto & entry : fs::recursive_directory_iterator(path))
{
int line_no = 0;
string line;
ifstream infile(path);
while(getline(infile, line))
{
++line_no;
auto pos = line.find(search);
if(pos != string::npos)
{
log_file << entry << ":" << line_no << ":" << line << endl;
}
}
// log_file << entry.path() << std::endl;
}
log_file.close();
}
ifstream infile(path); Should be ifstream infile(entry.path());.

How to read file in c++ using environment variable

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();
}

Why i can't use Windows Environment path with ofstream to write a text file?

Why i can't use Windows Environment path shortcut with ofstream to write a sample text file ?
\\ C:\Users\Me\AppData\Local\Temp\Test.txt
std::string Path = "%Temp%\\Test.txt"
ofstream myfile;
myfile.open (Path);
if (!myfile.is_open())
{
cout << "Could not create temp file." << endl;
}
myfile << "Hello World";
myfile.close();
myfile.is_open() always return false, also "%%Temp%%" and "\%Temp\%" not working.
I can get Temp path by Windows API, but i don't want to use API in this application.
Thank you
The %Temp% substitution is something done by some Windows programs, not by the C++ runtime. If you want to do this, just retrieve the environment variable yourself and build up a path. Something like this'll do it, but you'll want to add some error checking:
ostringstream tempfilepath;
tempfilepath << getenv("Temp") << '/' << "Test.txt";
ostream myFile;
myFile.open(tempfilepath.str());
...etc...

ifstream not working with variable parameter using C++11 and c_str() appended

Note: I am using the C++11 standard, so I don't see why this isn't working with or without c_str() appended.
I have the following code:
// open streams
ifstream in(input);
ofstream out(output);
// get which file to open
in.ignore(INT_MAX, ':'); // we don't need the beginning part
in.ignore(); // remove trailing whitespace
string fileLocation;
getline(in, fileLocation);
out << "Loading: " << fileLocation << endl;
cout << "Loading: " << fileLocation << endl;
// now that we know where the file is, load it:
ifstream file(fileLocation);
which reads from a file that looks vaguely like this
File: file.txt
(Subcommands below)
I know that I am pulling the correct filename because of the terminal output.
Anyway, I noticed that the stream wasn't opening properly, so I added this conditional to check:
if ( !file )
{
cout << "File wasn't loaded properly." << endl;
}
And sure enough, I see that message when running the program.
My question is this: how come, when I hard-code the file location, e.g. ifstream file("file.txt") it opens up no problem? How do I get this working properly?

Xcode: Where to put input file?

I'm trying to learn C++ and I'm using Xcode. I have the following main method:
int main()
{
const int SIZE = 256;
Expression* expression;
char paren, comma, line[SIZE];
ifstream fin("input.txt");
while (true)
{
symbolTable.init();
fin.getline(line, SIZE);
if (!fin)
break;
stringstream in(line, ios_base::in);
in >> paren;
cout << line << " ";
expression = SubExpression::parse(in);
in >> comma;
parseAssignments(in);
double result = expression->evaluate();
cout << "Value = " << result << endl;
// catch the exceptions
return 0;
}
}
Where do I put the file "input.txt" so the program can read it?
The filename parameter of ifstream is usually taken as a relative path to the working directory so that's where you should put the file.
If you launch the executable from a file manager, the working directory of the process will most likely be set to the directory the executable is in. In that case the text file should be in the same directory.
All relative paths (on OS X, any path that doesn't start with a slash, "/"), are interpreted relative to a process' working directory.
If you're running from the terminal, it should be in the terminal's current directory (i.e. ls should list it).
If you're running from inside XCode, there is a project setting for which directory should be the working directory.
You set that to wherever your file is, or move the file to wherever that directory is.