C++フォルダと書き込みファイルの作成

7059 ワード

C++フォルダと書き込みファイルの作成
  • フォルダの作成:一般的には、フォルダが存在するかどうかを判断してから作成する必要があります.
  • /*
     *          
     */
    //    
    #include
    #include
    
    //     
    //         ,      
    DIR* opendir (const char * path );
    
    /*
     *      
     */
    //    
    #include  
    //     
    //     ,        ,   -1
    int mkdir(const char *path, mode_t mode); 
    
  • ファイルを書くことについては、C++でいろいろな選択肢があります.ここではstd::ofstreamでファイルを書きます.具体的なコードは以下の通りです.
  • 例:フォルダが存在するか否かを判断し、存在しない場合に作成し、そのフォルダの下にファイル(Linux環境)
  • を書き込む.
    #include 
    #include 
    #include 
    #include 
    #include 
    
    #define FILE_PATH  "/home/linduo/test/"
    
    void doRealWork(const std::string& fileName, const std::string& str);
    
    int main()
    {
       doRealWork("test.txt", "Hello Lin Duo!");
    }
    
    void doRealWork(const std::string& fileName, const std::string& str)
    {
        if (!fileName.empty()) {
            if (NULL == opendir(FILE_PATH)) {
                // 0777        ,      chmod    /       
                if (-1 == ::mkdir(FILE_PATH, 0777)) {
                        return;
                    }
                }
                std::string file = NC_LOG_CMD_FILE_PATH + fileName;
                std::ofstream writeFile(file, std::ofstream::trunc);
                writeFile << str;
                writeFile << std::endl;
                writeFile.close();
            }
        }
    }