I am making a C++ program which should be able to list the files from particular directory and save each file name as a string(which will be processed further for conversion). Do I need array of strings? Which functionality should I use. The number of files is not fixed. Main thing is I can't enter the names manually. I must accept the names from the list generated.
Asked
Active
Viewed 115 times
2 Answers
0
In this case you want to use a vector
:
#include <vector>
#include <string>
using namespace std;
int main()
{
vector<string> file_names;
file_names.push_back("file1.txt");
file_names.push_back("file2.txt");
file_names.push_back("file3.txt");
file_names.push_back("file4.txt");
return 0;
}

Gillespie
- 5,780
- 3
- 32
- 54
-
-
-
Don't you think I need deque? If the following link is not wrong? http://stackoverflow.com/questions/10699265/how-can-i-efficiently-select-a-standard-library-container-in-c11 – arshpreet Dec 10 '14 at 16:53
-
You wouldn't enter in the file names manually, you would have a `string` variable that holds the value that you want to put into the vector. Where is this magical list of file names coming from, anyway? – Gillespie Dec 10 '14 at 18:58
-
Here is the program.https://gist.github.com/vivithemage/9517678 After "cout" want to save it into vector array so it can be used by magic++ for conversions of images. Basically I am listing all the .CR2 files and converting them into .PNG – arshpreet Dec 11 '14 at 03:01
0
Have you thought about using some command line tools to deal with this? Even input redirection will work for this. Example:
./Cpp < echo somedir/*
Where Cpp
is the name of your compiled binary, and somedir
is the directory you want to read from
Then in your c++ program, you simply use std::cin
to read each filename from standard in.
#include <vector>
#include <string>
#include <iterator> // std::istream_iterator, std::back_inserter
#include <algorithm> //std::copy
#include <iostream> // std::cin
int main()
{
std::vector<string> file_names;
// read the filenames from stdin
std::copy(std::istream_iterator<std::string>(std::cin), std::istream_iterator<std::string>(), std::back_inserter(file_names));
// print the filenames
std::copy(file_names.begin(), file_names.end(), std::ostream_iterator<std::string>(std::cout, "\n"));
return 0;
}

smac89
- 39,374
- 15
- 132
- 179
-
I don't think that is better option. I want to make code cross-platform. – arshpreet Dec 10 '14 at 17:08