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++;
        }
    
    }
Atrox
  • 107
  • 1
  • 6
  • 1
    Does this answer your question? [How to convert a std::string to const char\* or char\*](https://stackoverflow.com/questions/347949/how-to-convert-a-stdstring-to-const-char-or-char) – Quimby Sep 09 '21 at 16:26
  • 1
    Too much Yoda. `FILE* pipe = _popen(pCmd.c_str(), "rt"); if (!pipe) return;`. – Pete Becker Sep 09 '21 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. – Pete Becker Sep 09 '21 at 16:34
  • C++ has a filesystem library. I'd recommend using that instead of piggybacking on `dir`. – chris Sep 09 '21 at 16:42

1 Answers1

1

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

Aykhan Hagverdili
  • 28,141
  • 6
  • 41
  • 93