Я делаю простую утилиту для преобразования CSV-файла в EDL, но столкнулся со странной ошибкой, которая ставит меня в тупик. Я пытаюсь получить имя файла и открыть файл, если я закомментирую первую часть, как в примере ниже, вторая часть работает. Если я запускаю первую часть, она успешно получает имя файла, но даже не передавая имя собранного файла, но все же явно указывая его «C:\santor_4k.csv», myReadFile.open не открывает файл. Выходной файл по-прежнему работает нормально, просто он никогда не попадает в цикл if (myReadFile.is_open()).

void CMFCApplication3Dlg::OnBnClickedButtonOpen()
{

    // TODO: Add your control notification handler code here
    /*OPENFILENAME ofn;       // common dialog box structure
    char szFile[260];       // buffer for file name
    HWND hwnd;              // owner window
    HANDLE hf;              // file handle

    // Initialize OPENFILENAME
    ZeroMemory(&ofn, sizeof(ofn));
    ofn.lStructSize = sizeof(ofn);
    //ofn.hwndOwner = hwnd;
    ofn.lpstrFile = szFile;
    // Set lpstrFile[0] to '\0' so that GetOpenFileName does not 
    // use the contents of szFile to initialize itself.
    ofn.lpstrFile[0] = '\0';
    ofn.nMaxFile = sizeof(szFile);
    ofn.lpstrFilter = "CSV\0*.CSV\0";
    //ofn.lpstrFilter = "All\0*.*\0Text\0*.TXT\0";
    ofn.nFilterIndex = 1;
    ofn.lpstrFileTitle = NULL;
    ofn.nMaxFileTitle = 0;
    ofn.lpstrInitialDir = NULL;
    ofn.Flags = OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST;

    // Display the Open dialog box. 

    if (GetOpenFileName(&ofn) == TRUE)
        hf = CreateFile(ofn.lpstrFile,
        GENERIC_READ,
        0,
        (LPSECURITY_ATTRIBUTES)NULL,
        OPEN_EXISTING,
        FILE_ATTRIBUTE_NORMAL,
        (HANDLE)NULL);

    m_EchoText.Format(szFile);*/

    int counter = 0;
    int lastfcc = 0;
    int fcc;
    ifstream myReadFile;
    myReadFile.open("C:\\santor_4k.csv");
    std::ofstream outfile;
    outfile.open("C:\\santor_4k_r3_resolve.edl", std::ofstream::out | std::ofstream::app);
    char output[260];
    //resolve
    cout << "TITLE: ( no title )" << endl << endl;
    outfile << "TITLE: ( no title )" << endl << endl;
    //revival
    //outfile << "TITLE: ( no title )" << endl;
    //outfile << "FCM: NON - DROP FRAME"<<endl << endl;;
    if (myReadFile.is_open()) {
        while (!myReadFile.eof()) {
            int first;
            int second;
            char lastTC[40];
            myReadFile >> output;
            //cout << int(output[0]) << endl;
            if (int(output[0]) > 47 && int(output[0]) < 58)
            {// cout << output << endl; 
                std::string str = output;
                std::size_t found = str.find(",");
                if (found != std::string::npos){
                    //cout <<"first comma" << found << endl; 
                    first = found + 1;
                }
                found = str.find(",", found + 1);
                if (found != std::string::npos) {
                    //cout << "second comma" << found << endl; 
                    second = found - first;
                }
                std::string  fccstring = str.substr(first, second);
                //cout << "fccString=" << fccstring<<endl;
                fcc = stoi(fccstring); //+1 for revival ?
                toTimeCode(lastfcc);
                strcpy_s(lastTC, timecode);
                toTimeCode(fcc);
                cout << setfill('0') << setw(3) << counter << "  001      V     C " << lastTC << " " << timecode << " " << lastTC << " " << timecode << " " << endl << endl;
                //resolve
                if (counter>0)outfile << setfill('0') << setw(3) << counter << "  001      V     C " << lastTC << " " << timecode << " " << lastTC << " " << timecode << " " << endl << endl;
                //revival
                //if (counter>0)outfile << setfill('0') << setw(3) << counter << "   title     V     C " << lastTC << " " << timecode << " " << lastTC << " " << timecode<<"\r";

                lastfcc = fcc;
                counter++;
            }


        }
    }
    myReadFile.close();
    outfile.close();
    //std::cout << "Press ENTER to continue...";
    //std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
    UpdateData(FALSE);
}
-1
Simon 2 Дек 2014 в 21:00
Если проблема не может прочитать/открыть/записать файл, вам не нужно показывать весь этот код. Просто выполните простое открытие/закрытие или запишите пару байтов в файл, а затем посмотрите, работает ли это. Продираться через весь этот код после GetOpenFileName - это слишком...
 – 
PaulMcKenzie
2 Дек 2014 в 21:21

2 ответа

Что вы получите в szFile после выполнения GetOpenFileName(&ofn)? Вы также должны memset(szFile, 0, sizeof(szFile)); перед вызовом GetOpenFileName.

0
Pierre 2 Дек 2014 в 21:18

Я разобрался со своей проблемой, думаю, никогда не следует копировать пример, не понимая его, вот эту часть:

If (GetOpenFileName(&ofn) == TRUE) hf = CreateFile(ofn.lpstrFile, GENERIC_READ, 0, (LPSECURITY_ATTRIBUTES)NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, (HANDLE)NULL);

Уже открывает файл, поэтому, когда я снова открыл его, это не сработало. Удалив его, я решил проблему

0
Simon 2 Дек 2014 в 21:45