簡體   English   中英

如何在c ++中已經存在的情況下通過增加索引來創建新文件夾

[英]how to create a new folder with increasing its index if it already exist in c++

偽代碼:

for(int i=0;i<m_iNumOfClass;i++) {

    char str[200];

    if(iterk doesn't exist)
        sprintf(str, "iterk\\HMMtransiMean%d.txt", i);

    iter(iterk exist)
    mkdir(iterk+1)
    sprintf(str, "iterk+1\\HMMtransiMean%d.txt", i);
}

這是我想做的偽代碼。

我要創建一個名為iterk1的文件夾(如果該文件夾不存在)。 但是,如果存在,則創建一個名為iterk2的文件夾。 然后,在剛剛創建的文件夾中創建一個名為HMMtransiMean%d的txt文件。

我該怎么做? 請幫我。

如果可以使用boost :: filesystem(作為πάνταῖεῖ建議),則:

#include <string>
#include <fstream>
#include <boost/filesystem.hpp>

using namespace boost::filesystem;

int main()
{
    int m_iNumOfClass(2);

    path path_template("/tmp"); //Maybe you should use "C:\\tmp" instead
    path_template /= "iter";

    path directory;

    for(int i=0; i<m_iNumOfClass; i++) {

        int directory_index = 0;

        do
        {
            directory_index++;
            directory = path_template;
            directory += std::to_string(directory_index);
        } while (!create_directory(directory));

        directory /= "HMMtransiMean";
        directory += std::to_string(i) + ".txt";

        std::string filename(directory.string());

        std::ofstream outfile (filename);

        outfile.close();

    }

    return 0;
}

注意:此解決方案不需要增強...

我假設您正在使用Windows平台(因為您使用"\\\\" ):

要考慮的第一個有用函數是_mkdirdoc )。

您可以使用非零值來確定是否創建了文件夾。

要創建文件,您可以使用fopendoc

這對我在Windows上有效,但也應該在Linux上有效(將direct.h更改為#include <sys/stat.h>#include <sys/types.h>進行較小的include更改以具有mkdir):

#include <iostream>
#include <sstream>
#include <direct.h>
#include <cstdio>
#include <string>
using namespace std;

int main() {
    const string pref = "iterk";
    string path = pref;
    stringstream suffix;
    int i=0;
    int res = -1;
    do{     
        res = mkdir(path.c_str());
        if( res == 0){
            path = path + "/HMMtransiMean" + suffix.str() + ".txt";
            break;
        }
        else{
            ++i;
            suffix.str(string());
            suffix << i;
            path = pref + suffix.str();
        }
    } while (EEXIST == errno);

    FILE * stream;

    if( (stream = fopen(path.c_str(), "w+" )) == NULL ) // C4996
        printf( "The file was not opened\n" );
    else
        printf( "The file was opened\n" );
    string data = "Hi";
    int numwritten = fwrite( data.c_str() , sizeof( char ), data.length() , stream );
    printf( "Wrote %d items\n", numwritten );
    fclose( stream );
    return 0;
}

如果僅在Windows上使用它,則應該使用_mkdir函數(如我之前所述)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM