How to create many binary file within a loop ?

This code was written, which take a directory then look for the files inside. it aims to create binary files for each file found by taking it filename. I want to create these file first so as to write some data inside them later.

However, the code is not running as expected. and the binary file are not created this the issue.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
      #include <vector>
    #include <string>
    #include <iostream> // for standard I/O
    #include <string>   // for strings
    #include <iomanip>  // for controlling float print precision
    #include <sstream>  // string to number conversion
    #include <fstream>

    void getDir(string d, vector<string> & f)
    {
        FILE* pipe =  NULL;
        string pCmd = "dir /B /S " + string(d);
        char buf[256];

        if( NULL == (pipe = _popen(pCmd.c_str(),"rt")))
        {
            cout<<"Error"<<endl;
            return;
        }

        while (!feof(pipe))
        {
            if(fgets(buf,256,pipe) != NULL)
            {
                f.push_back(string(buf));
            }

        }

        _pclose(pipe);
    }

    void replaceExt(string& s, const string& newExt) {

       string::size_type i = s.rfind('.', s.length());

       if (i != string::npos) {
          s.replace(i+1, newExt.length(), newExt);
       }
    }

    using namespace std;

    int main(int argc, char* argv[])
    {
        vector<string> files;
        string path = "C:\\repo";
        getDir(path, files);
        vector<string>::const_iterator it = files.begin();
        cout<<"Creating bin files "<<endl;

        ofstream myOfstream;

        while( it != files.end())
        {
            string fileName = (string) *it;
            replaceExt(fileName, "bin");
            cout << fileName << '\n';

            std::stringstream ss;
            ss << fileName << "" ;
            myOfstream.open(ss.str(),  fstream::binary);
            if ( !myOfstream )
            {
                std::cerr << "Error: failed to create file " << '\n';
                break;
            }

            myOfstream.close();

            it++;
        }

        return 0;
    }
However, the code is not running as expected.

Not a particular precise description of the problem.

Your task consists of tho steps.
1. Getting the filenames in a directory
2. Looping through all the filenames and create a file for it

Does the first step work?
Do you get all the filenames?
You can insert trace statements (or run it in a debugger) to examine program state as it executes.

It's a little unorthodox in it's approach. If I were to start changing it based on just what you've given, I'd rewrite it.
getting the filenames and creating the binary file with the same filename while changing the extension.

the task is to loop through files like images in the dir the names change the extension then create for each image its own binary file

I get the file names, but the creation of the binary files doesn't succeed
I got (Error: failed to create file)
it's simple the aim is to create for each element in the vector its binary file
It could simply be that the fgets leaves the newline at the end of the line. You should remove it.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <cstdio>  // _popen, _pclose
#include <cstring> // strcspn
using namespace std;

bool getDir(string dir, vector<string>& files) {
    string cmd = "dir /B /S " + dir;
    FILE *pipe = _popen(cmd.c_str(), "r");
    if (!pipe) {
        cerr << "Error opening pipe\n";
        return false;
    }
    char line[1000];
    while (fgets(line, sizeof line, pipe) != NULL) {
        line[strcspn(line, "\n")] = '\0';
        files.push_back(line);
    }
    _pclose(pipe);
    return true;
}

void replaceExt(string& str, const string& ext) {
    size_t i = str.rfind('.');
    if (i != string::npos)
        str.replace(i + 1, string::npos, ext);
    else
        str += '.' + ext;
}

int main() {
    vector<string> files;

    if (!getDir("C:/repo", files))
        return -1; 

    for (string filename: files) {
        replaceExt(filename, "bin");
        cout << filename << '\n';
        //ofstream fout(filename, ofstream::binary);
    }
}

Last edited on
The task is to loop through files like images in the dir the names change the extension then create for each image its own binary file

You're probably using the wrong tool. Use a shell script. In Bash:

<<(find . -type f -name "*.jpg" -o -name "*.png") \
while read line ; do touch ${line%.*}.bin; done


(I don't know how to do this in Windows batch.)

But if you really wanted to do this in C++, try something like this:
I've left creating the files to you, so that you can run it without fear of messing up your filesystem.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
#include <filesystem>
#include <iostream>

namespace fs = std::filesystem;

void
process_dirent(fs::directory_entry const &entry)
{
  if (entry.is_regular_file()) {
    fs::path p = entry.path();
    std::cout << p.replace_extension(".bin") << '\n';
    // NOTE: create the file here ...
  }
}

int
usage(char const **argv)
{
  std::cerr << "usage: " << *argv << " directory\n";
  return 1;
}

int
main(int argc, char **argv)
{
  if (argc != 2)
    return usage(argv);

  std::error_code ec;

  for (auto &s : fs::recursive_directory_iterator(argv[ 1 ], ec))
    process_dirent(s);

  if (ec) {
    std::cerr << ec.message() << '\n';
    return 1;
  }
}

Last edited on
Topic archived. No new replies allowed.