1

したがって、これは現在の名前でファイルをファイル名として保存する私の機能です。

cur_date = curDate(); 
cur_date.append(".txt");
myfile.open(cur_date.c_str(), std::ios::out | std::ios::app);

if (myfile.is_open()) 
{ 
    std::cout << message; 
    myfile << message; myfile << "\n"; 
    answer.assign("OK\n"); 
    myfile.close(); 
} else 
{ 
    std::cout << "Unable to open file\n" << std::endl; 
    answer.assign("ERR\n"); 
}

そして、これは日付関数です:

const std::string server_funcs::curDate() 
{ 
    time_t now = time(0); 
    struct tm tstruct; 
    char buf[80]; 
    tstruct = *localtime(&now);

    strftime(buf, sizeof(buf), "%Y-%m-%d_%X", &tstruct);

    return (const std::string)buf; 
}

私の問題は、open() 関数が新しいファイルを作成していないため、if 句の else 部分に移動することです。しかし、名前または静的入力に別の char* を使用すると、正常に動作します。だから私はそれがcurDate()関数と関係があると考えましたが、私は何を知りません...また、cur_date().c_str()を印刷すると、うまく表示されます..

4

1 に答える 1

2

関数 curDate() は、"2013-10-15_19:09:02" の形式の文字列を返します。この文字列にはコロンが含まれているため、許可されたファイル名ではありません。それが open 関数が失敗する理由です。

コロンをドットに置き換えるには (たとえば)、次のコードに変更します。このコードは、コロンの代わりにドットを含む別の時間形式を指定します:

#include <algorithm>

const std::string server_funcs::curDate() 
{ 
    time_t now = time(0); 
    struct tm tstruct; 
    char buf[80]; 
    tstruct = *localtime(&now);

    strftime(buf, sizeof(buf), "%Y-%m-%d_%H.%M.%S", &tstruct);

    std::string result = buf;
    return result; 
}
于 2013-10-15T17:10:28.687 に答える