0

im trying to make a simple program that list all txt file in the directory then append hello world in them but i face an issue while passing the vector into WriteFiles Function

this is the following code i've tried to fix it for a while any oil be grateful for any help

 #define _CRT_SECURE_NO_WARNINGS #include <string> #include <vector> #include <iostream> #include <windows.h> #include <fstream> using namespace std; void ListFiles(vector<string>& f) // list all files { FILE* pipe = NULL; string pCmd = "dir /b /s *.txt "; char buf[256]; if (NULL == (pipe = _popen(pCmd.c_str(), "rt"))) { return; } while (!feof(pipe)) { if (fgets(buf, 256, pipe) != NULL) { f.push_back(string(buf)); } } _pclose(pipe); } void WriteFiles (const char* file_name) { std::ofstream file; file.open(file_name, std::ios_base::app); // append instead of overwrite file << "Hello world"; file.close(); } int main() { vector<string> files; ListFiles(files); vector<string>::const_iterator it = files.begin(); while (it != files.end()) { WriteFiles(*it); // the issue is here cout << "txt found :" << *it << endl; it++; } } 
4
  • 1
    Does this answer your question? How to convert a std::string to const char* or char* Commented Sep 9, 2021 at 16:26
  • 1
    Too much Yoda. FILE* pipe = _popen(pCmd.c_str(), "rt"); if (!pipe) return;. Commented Sep 9, 2021 at 16:31
  • 1
    This doesn't address the question, but get in the habit of initializing objects with meaningful values rather than default constructing them and immediately overwriting the default values. In this case, that means changing std::ofstream file; file.open(file_name, std::ios_base::app); to std::ofstream file(file_name, std::ios_base::app);. Also, you don't have to call file.close(). The destructor will do that. Commented Sep 9, 2021 at 16:34
  • C++ has a filesystem library. I'd recommend using that instead of piggybacking on dir. Commented Sep 9, 2021 at 16:42

1 Answer 1

1

WriteFiles(it->c_str()); will fix the problem. Iterators act a lot like pointers, so that's how you access a method indirectly.

Sign up to request clarification or add additional context in comments.

1 Comment

@Atrox I am sorry, I can't debug it for you right now. Use your debugger to see what's up. Good luck

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.