How to run a c++ program multiple times with different input files? - c++

I'm new to C++ and writing my master thesis and would really appreciate any help I can get!
I have a program that reads a txt file, then does a bunch of calculations, and returns a new txt file. The thing is that I want to run this program for 100+ different input files. Now I have to change the name of the input file in the code, but I would like to have it run for all the input files in my folder by itself.
I am using Visual Studio, but with little C++ experience.
Thanks :)

See this snippet. Since you are using MSCV, you need to enable MFC in configuration for this console application. Also add #include "afx.h" in #include "stdafx.h" where CFileFind is defined. PopulateFromFolder() should auto load the files into the vector files.
#include "stdafx.h"
#include <iostream>
#include <string>
#include <fstream>
#include <vector>
using namespace std;
void PopulateFromFolder(string path, vector<string>& files)
{
CFileFind finder;
CString fileName;
fileName.Format(L"%s*.*", CString(path.c_str()));
BOOL bOk = finder.FindFile(fileName);
while (bOk)
{
bOk = finder.FindNextFile();
if (finder.IsDots())
{
continue;
}
if (!finder.IsDirectory())
{
CString strFileName = finder.GetFileName();
files.push_back(CStringA(strFileName).GetString());
}
}
finder.Close();
}
int main()
{
vector<string> files;
string path = "D:\\MyFolder\\";
PopulateFromFolder(path, files);
auto a = path + files[0];
int i = 0;
while (i< files.size()-1)
{
cout << "processing " << files[i + 1] << endl;
ifstream fs(path+files[i++]);
if (fs.is_open())
{
//do something
}
fs.close();
}
return 0;
}
Output:

Using bash you can run them using:
$ for file in /Data/*.txt; do /path/your_program $file; done

You can define format for your input files names and put then into some directory. For example,
Input1.txt
Input2.txt
...
Input111.txt
Then use some kind of for loop:
for(int i = 1; i <= 111; ++i)
{
ifstream file("Input" + std::to_string(i) + ".txt");
if (file.is_open())
Operate(file);
}
If you don't know the exact number of files, you can check whether the file was openen by is_open() method. This way files with some numbers can be absent. You just loop for some max possible input file id.
This was a solution which doesn't require any dependencies. But if you don't mind it, you actually may consider Boost.Filesystem. Here is an example.

You can try to use std::experimental::filesystem (http://en.cppreference.com/w/cpp/experimental/fs). I guess that directory_iterator from this library can be useful for you - it allows you to iterate over all files in a given directory. Have a look at the example provided in the documentation: http://en.cppreference.com/w/cpp/experimental/fs/directory_iterator.
However, you have to make sure that you are compiling your code with a new standard (C++ 17).
Another way is to make for example a separate file containing a list of the names of all files that you want to work on. Then, you can read this list and for every file do what you need.

Related

Having trouble processing a file from my documents in my code?

I have searched for this around the web and here but I can't seem to figure out what I am doing wrong.
I am simply trying get better with file processing and c++.
For practice I am trying to grab a text file from a game folder and make a copy of it.
Here is my code (that can't access the file).
#include <fstream>
#include <iostream>
#include <string>
using namespace std;
int main()
{
//define / open files
ifstream my_input_file;
ofstream my_output_file;
string filepath = "C:/Users/David Laptop/Documents/my games/oblivion/RenderInfo.txt";
my_input_file.open(filepath);
if (my_input_file.is_open())
{
cout << "opened\n";
my_output_file.open("output_file.txt", ofstream::trunc);
char c;
my_input_file.get(c);
while (my_input_file)
{
my_output_file.put(c);
my_input_file.get(c);
}
my_input_file.close();
my_output_file.close();
}
else
{
cout << "FAIL\n";
}
cin.get();
return 0;
}
This seemed to work with both text files and .ini files when in the project directory but I am having issues properly getting to other directiorys?
Any ideas?
thanks!
Your code is perfectly valid and it works - I tried it with my own file instead of yours, in the line
string filepath = "C:/Users/David Laptop/Documents/my games/oblivion/RenderInfo.txt";
So you have not such file or it is not in the given path or you have not such path.
Correct it in that line and it will be OK.
Tip: Find your file in Windows Explorer, press (and keep pressing) Shift) and right-click on this file. From the context menu then choose Copy as path and then paste it to your code. But be carefull - you have to change every backslash (\) to a forward slash (/) (as in your code) or use double backslashes (\\) instead of a single one.

Unable to open file.txt with c++

I've looked up similar posts here, but none seem to be doing the job for my question. I'm basically trying take a sequence of words in a .txt file and put each word in a vector, and printing each value afterwards. For example, we have I love racing cars in array.txt, and I want my vector to have "I" at position 0, "love" at 1 and so on. Unfortunately, the code does not access "array.txt", so it never executes the code in the if condition.
Now I've heard that by using the fstream library it should work just fine, but the file is never found. I suspect that it doesn't work because it cannot find the path, but I have never opened files in C++. Also, I have not put my file anywhere in my project folder.
Some changes I've already tried:
file.open("array.txt");
omitting file.close();
include "C:\array.txt"; (with the # in front)
file.open("C:\array.txt")
And I'm using Windows 10, if this matters.
#include <iostream>;
#include <string>;
#include <vector>;
#include <fstream>;
//#include <"C:\Users\Samer El-Hage\Documents">;
using namespace std;
void main(){
vector<string> v (10);
ifstream file;
file.open("C:\array.txt", ios::in);
if (file.is_open())
{
for (int i = 0; i < 3; i++)
{
file >> v[i];
}
file.close();
}
else cout << "Could not access file.";
for (int i = 0; i < 3; i++)
{
cout << v[i] << " ";
}
}
This code prints "Could not access file."
The file cannot be opened because the file system can't find the file named "[Bell]rray.txt". the character sequence '\a' is the "Make my computer Beep" character.
Use either forward slashes: "C:/array.txt", an escaped backslash: "C:\\array.txt" or a raw string literal: R"(C:\array.txt)"
The file must also exist at the specified location. If you do not provide a drive and just say "array.txt" the location defaults to wherever the executable is (or in an IDE, the Working Directory).
Also, you have unnecessary semi-colons after your includes. (In fact, in a Treat Warnings as Errors setup, this won't compile!)
I got it! I had not put the .txt file in my folder with the source code, which, strangely enough, was not mentioned in my previous search results... I got to search better!
\a simply turns the computer beep on. Try writing "C:\\array.txt" instead in the open call.
Try not calling open explicitly:
ifstream file ("array.txt");
Look at the examples here:1

c++ ofstream write_to_log.open (" relative path + array");

I want the line below to write a new file using the content given in the array
but into a new folder named logs:
char log_file_name[100]; /* this array contains the name of a new file */
ofstream write_to_log;
write_to_log.open (relative path, log_file_name , fstream::app);
How do I get it working ?
You can use CreateDirectory for creating folders with VC++ in Windows.
#include <windows.h>
#include <string>
#include <fstream>
using namespace std;
int main() {
string path = "C:\\users\\folder";
CreateDirectory(path.c_str(), NULL);
char log_file_name[100] = "log.txt";
path += '\\';
path += log_file_name;
ofstream write_to_log(path.c_str(), fstream::app);
return 0;
}
The NULL refers to a security attributes structure that you may have to create. More details at MSDN here and in this answer.
You can save your self a lot of potential trouble and replace char log_file_name[100]; with std::string log_file_name; The benefits of string are many, the most important here are they resize and they make appending really easy. The string does everything a char array does and a whole lot of extras. In virtually all cases, you should chose a string over a char array.
string path;
string log_file_name;
With the path and the file name as strings
path += "\\" + log_file_name
ofstream write_to_log(path, fstream::app);
if (write_to_log)
{ // file is open and looks writable (have to start writing to be sure)
// do stuff. Or not. It's a free country.
}
else
{ // file didn't open
// Handle error
}
All done and the file, if it exists and is writable, is open and ready to go. Always check the state of a stream when you use it. SO is littered with questions from people who didn't and got confused by the result.
On older compilers you may have to change the create and open line slightly:
ofstream write_to_log(path.c_str(), fstream::app);

Cannot open file with relative path? (C++ ifstream)

I know this seems like a simple question, but I tried everything I can think of to no avail to something that shouldn't have been a problem in the first place.
This is a small C++ program that opens a file. When I open it with its absolute filepath, it works fine. With a relative path, however, it stops working.
Here's the file path of the program and the files I'm trying to read:
C++ program: "/Users/Baggio/C++/Lab0/Lab0/Lab0/main.cpp"
Files: /Users/Baggio/C++/Lab0/Lab0/Lab0/result.txt, /Users/Baggio/C++/Lab0/Lab0/Lab0/dict.txt
Here's the code snippet:
#include <iostream>
#include <fstream>
#include <iomanip>
#include <string>
#include <cstdlib>
using namespace std;
int main(int argc, const char * argv[]) {
// string dict_filename = "/Users/Baggio/C++/Lab0/Lab0/Lab0/dict.txt";
// string result_filename = "/Users/Baggio/C++/Lab0/Lab0/Lab0/result.txt";
string dict_filename_string = "dict.txt";
string result_filename_string = "result.txt";
const char* dict_filename = dict_filename_string.c_str();
const char* result_filename = result_filename_string.c_str();
// open files
ifstream dict_file(dict_filename, ifstream::in);
ifstream result_file(result_filename, ifstream::in);
if (!dict_file || !result_file) {
cerr << "File could not be opened." << endl;
exit(1);
}
}
Result of execution
File could not be opened.
I'm sure I've done all the includes right, and the data types right for the ifstream constructor arguments. The only thing I can think of worth mentioning is the system I'm on: I'm on a Mac and I'm using XCode6 as my IDE.
Also, I've tried to move the files' location (results.txt and dict.txt) to these locations to no avail:
/Users/Baggio/C++/Lab0/Lab0/Lab0/
/Users/Baggio/C++/Lab0/Lab0/
/Users/Baggio/C++/Lab0/
/Users/Baggio/C++/
Thanks for your help guys!! Any suggestions or thoughts appreciated.
Print out your current working directory when you run the program:
char buffer[256];
char *val = getcwd(buffer, sizeof(buffer));
if (val) {
std::cout << buffer << std::endl;
}
This will tell you where you are running your program from and thus why the path doesn't match for relative paths. A relative path is relative to the current working directory, not to where your binary is located.
If you want to make the path relative to the location of the binary then you will have to do that yourself. Many programming languages offer this as an option, but it is not built-in to C++. You can do this by finding the executable using the argv[0] from main. Then you need to drop the file component of the executable path and replace it with the file name that you are interested in.
Since C++17, you can use std::filesystem::current_path() instead of getcwd.
std::cout << std::filesystem::current_path() << std::endl;

Open file by its full path in C++

I want the user to give me the full path where the file exists and not just the file name. How do I open the file this way?
Is it something like this:
ifstream file;
file.open("C:/Demo.txt", ios::in);
This doesn't seem to work.
Normally one uses the backslash character as the path separator in Windows. So:
ifstream file;
file.open("C:\\Demo.txt", ios::in);
Keep in mind that when written in C++ source code, you must use the double backslash because the backslash character itself means something special inside double quoted strings. So the above refers to the file C:\Demo.txt.
You can use a full path with the fstream classes. The folowing code attempts to open the file demo.txt in the root of the C: drive. Note that as this is an input operation, the file must already exist.
#include <fstream>
#include <iostream>
using namespace std;
int main() {
ifstream ifs( "c:/demo.txt" ); // note no mode needed
if ( ! ifs.is_open() ) {
cout <<" Failed to open" << endl;
}
else {
cout <<"Opened OK" << endl;
}
}
What does this code produce on your system?
The code seems working to me. I think the same with #Iothar.
Check to see if you include the required headers, to compile. If it is compiled, check to see if there is such a file, and everything, names etc, matches, and also check to see that you have a right to read the file.
To make a cross check, check if you can open it with fopen..
FILE *f = fopen("C:/Demo.txt", "r");
if (f)
printf("fopen success\n");
For those who are getting the path dynamicly... e.g. drag&drop:
Some main constructions get drag&dropped file with double quotes like:
"C:\MyPath\MyFile.txt"
Quick and nice solution is to use this function to remove chars from string:
void removeCharsFromString( string &str, char* charsToRemove ) {
for ( unsigned int i = 0; i < strlen(charsToRemove); ++i ) {
str.erase( remove(str.begin(), str.end(), charsToRemove[i]), str.end() );
}
}
string myAbsolutepath; //fill with your absolute path
removeCharsFromString( myAbsolutepath, "\"" );
myAbsolutepath now contains just C:\MyPath\MyFile.txt
The function needs these libraries: <iostream> <algorithm> <cstring>.
The function was based on this answer.
Working Fiddle: http://ideone.com/XOROjq
A different take on this question, which might help someone:
I came here because I was debugging in Visual Studio on Windows, and I got confused about all this / vs \\ discussion (it really should not matter in most cases).
For me, the problem was: the "current directory" was not set to what I wanted in Visual Studio. It defaults to the directory of the executable (depending on how you set up your project).
Change it via: Right-click the solution -> Properties -> Working Directory
I only mention it because the question seems Windows-centric, which generally also means VisualStudio-centric, which tells me this hint might be relevant (: