2012-07-18 139 views
-4

可能重複:
Splitting a string in C++分割字符串C++

我有那份文件的程序。

我有一個字符串,它是一個目錄路徑,但它可能只是一個文件名。例如:

rootdirname\childdirname\filename.ini

,或者它可能是:

filename.ini

進出口仍然很新的C++,我需要拆就\字符串,並與MKDir創建目錄。

任何一個知道如何拆分字符串?

+4

輪你怎麼看難? Duplicate:[在C++中分割字符串](http://stackoverflow.com/questions/236129/splitting-a-string-in-c),[如何在C++中標記字符串?](http:// stackoverflow .com/questions/53849/how-do-i-tokenize-a-string-in-c?lq = 1)等等。 – 2012-07-18 08:11:03

+0

字符串是一個char數組,所以遍歷數組,直到你遇到'/'並開始連接來自這裏的字符在一個臨時字符數組中,每當你遇到新的'/'時清除臨時數據,最後你會在臨時字符數組中有filename.ini。或者直接從and開始,並向後迭代並取出第一個臨時數組而不清除它 – 2012-07-18 08:13:09

+0

,然後您可以查看strtok庫以獲取想法 – 2012-07-18 08:15:33

回答

1

我不知道你是如何定義你的字符串,但如果它是一個char *您可以使用的strtok 。 http://www.cplusplus.com/reference/clibrary/cstring/strtok/

+0

這幾天strtok()是線程安全的嗎? – 2012-07-18 09:07:23

+0

考慮到我認爲這不是一個問題的問題。否則,好點,我不認爲它是線程安全的。 – Chefire 2012-07-18 12:22:36

0

改造Linux上

#include <string> 
#include <sys/statfs.h> 

bool existsDir(const std::string& dir) { 
    return existsFile(dir); 
} 

bool existsFile(const std::string& file) { 
    struct stat fileInfo; 
    int error = stat(file.c_str(), &fileInfo); 
    if(error == 0){ 
     return true; 
    } else { 
     return false; 
    } 
} 

bool createDir(std::string dir, int mask = S_IRWXU | S_IRWXG | S_IRWXO) { 
    if(!existsDir(dir)) { 
     mkdir(dir.c_str(), mask); 
     return existsDir(dir); 
    } else { 
     return true; 
    } 
} 

bool createPath(std::string path, int mask = S_IRWXU | S_IRWXG | S_IRWXO) { 
    if(path.at(path.length()-1) == '/'){ 
     path.erase(path.length()-1); 
    } 
    std::list<std::string> pathParts; 

    int slashPos = 0; 
    while(true) { 
     slashPos = path.find_first_of("/", slashPos+1); 
     if(slashPos < 0) 
      break; 
     std::string pp(path.substr(0, slashPos)); 
     pathParts.push_back(pp); 
    } 
    std::list<std::string>::const_iterator pp_cit; 
    for(pp_cit=pathParts.begin(); pp_cit!=pathParts.end(); ++pp_cit){ 
     createDir((*pp_cit), mask); 
    } 

    createDir(path, mask); 
    return existsDir(path); 
}