C ++ fstream выводит неверные данные - PullRequest
2 голосов
/ 11 ноября 2011

Контекст первый:

Моя программа выполняет некоторые параллельные вычисления, которые регистрируются в файле. Потоки сгруппированы по блокам (я использую CUDA). Файл журнала формируется следующим образом:

#begin run
({blockIdx,threadIdx}) {thread_info}
({blockIdx,threadIdx}) {thread_info}
...
#end run

Я написал функцию, которая должна читать файл журнала и сортировать каждое сообщение о запуске по потоку.

//------------------------------------------------------------------------------
// Comparison struct for log file sorting
//------------------------------------------------------------------------------
typedef struct
{
    bool operator()(const string &rString1 , const string &rString2)
    {
        int closeParenthesisLocalition1 = rString1.find_first_of(')');
        int closeParenthesisLocalition2 = rString2.find_first_of(')');
        int compResult = rString1.compare(0 , closeParenthesisLocalition1 + 2 , rString2 , 0 , closeParenthesisLocalition2 + 2);
        return (compResult < 0);
    }
} comp;

//------------------------------------------------------------------------------------
// Sort the log file. Lines with same prefix (blockIdx,ThreadIdx) will be grouped in file per run.
//------------------------------------------------------------------------------------
void CudaUnitTest::sortFile()
{
    comp comparison;
    deque<string> threadsPrintfs;
    ifstream inputFile(m_strInputFile);
    assert(inputFile.is_open());

    //Read whole input file and close it. Saves disk accesses.
    string strContent((std::istreambuf_iterator<char>(inputFile)), std::istreambuf_iterator<char>());
    inputFile.close();

    ofstream outputFile(m_strOutputFile);
    assert(outputFile.is_open());

    string strLine;
    int iBeginRunIdx = -10; //value just to addapt on while loop (to start on [0])
    int iBeginRunNewLineOffset = 10; //"idx offset to a new line char in string. Starts with the offset of the string "#begin run\n".
    int iEndRunIdx;
    int iLastNewLineIdx;
    int iNewLineIdx;

    while((iBeginRunIdx = strContent.find("#begin run\n" , iBeginRunIdx + iBeginRunNewLineOffset)) != string::npos)
    {
        iEndRunIdx = strContent.find("#end run\n" , iBeginRunIdx + iBeginRunNewLineOffset);
        assert(iEndRunIdx != string::npos);

        iLastNewLineIdx = iBeginRunIdx + iBeginRunNewLineOffset;
        while((iNewLineIdx = strContent.find("\n" , iLastNewLineIdx + 1)) < iEndRunIdx)
        {
            strLine = strContent.substr(iLastNewLineIdx + 1 , iNewLineIdx);
            if(verifyPrefix(strLine))
                threadsPrintfs.push_back(strLine);
            iLastNewLineIdx = iNewLineIdx;
        }

        //sort last run info
        sort(threadsPrintfs.begin() , threadsPrintfs.end() , comparison);
        threadsPrintfs.push_front("#begin run\n");
        threadsPrintfs.push_back("#end run\n");

        //output it
        for(deque<string>::iterator it = threadsPrintfs.begin() ; it != threadsPrintfs.end() ; ++it)
        {
            assert(outputFile.good());
            outputFile.write(it->c_str() , it->size());
        }
        outputFile.flush();
        threadsPrintfs.clear();
    }

    outputFile.close();
}

Проблема в том, что в результирующем файле много мусорных данных. Например, входной файл журнала размером 6 КБ сгенерировал выходной журнал размером 192 КБ! Похоже, выходной файл имеет много повторений входного файла. Однако при отладке кода deque показывал правильные значения до и после сортировки. Я думаю, что что-то не так с самой записью ofstream.

Редактировать: функция не работает параллельно.

1 Ответ

0 голосов
/ 12 ноября 2011

Просто чтобы показать окончательный код.Обратите внимание на изменение в substr, теперь вместо индекса он получает длину.

//------------------------------------------------------------------------------------
// Sort the log file. Lines with same prefix (blockIdx,ThreadIdx) will be grouped in file per run.
//------------------------------------------------------------------------------------
void CudaUnitTest::sortFile()
{
comp comparison;
deque<string> threadsPrintfs;
ifstream inputFile(m_strInputFile);
assert(inputFile.is_open());

//Read whole input file and close it. Saves disk accesses.
string strContent((std::istreambuf_iterator<char>(inputFile)), std::istreambuf_iterator<char>());
inputFile.close();

ofstream outputFile(m_strOutputFile);
assert(outputFile.is_open());

string strLine;
int iBeginRunIdx = -10; //value just to addapt on while loop (to start on [0])
int iBeginRunNewLineOffset = 10; //"idx offset to a new line char in string. Starts with the offset of the string "#begin run\n".
int iEndRunIdx;
int iLastNewLineIdx;
int iNewLineIdx;

while((iBeginRunIdx = strContent.find("#begin run\n" , iBeginRunIdx + iBeginRunNewLineOffset)) != string::npos)
{
    iEndRunIdx = strContent.find("#end run\n" , iBeginRunIdx + iBeginRunNewLineOffset);
    assert(iEndRunIdx != string::npos);

    iLastNewLineIdx = iBeginRunIdx + iBeginRunNewLineOffset;
    while((iNewLineIdx = strContent.find("\n" , iLastNewLineIdx + 1)) < iEndRunIdx)
    {
        strLine = strContent.substr(iLastNewLineIdx + 1 , iNewLineIdx - iLastNewLineIdx);
        if(verifyPrefix(strLine))
            threadsPrintfs.push_back(strLine);
        iLastNewLineIdx = iNewLineIdx;
    }

    //sort last run info
    sort(threadsPrintfs.begin() , threadsPrintfs.end() , comparison);
    threadsPrintfs.push_front("#begin run\n");
    threadsPrintfs.push_back("#end run\n");

    //output it
    for(deque<string>::iterator it = threadsPrintfs.begin() ; it != threadsPrintfs.end() ; ++it)
    {
        assert(outputFile.good());
        outputFile.write(it->c_str() , it->size());
    }
    threadsPrintfs.clear();
}

outputFile.close();
}
...