`freopen`并检查文件是否可写

时间:2014-03-12 02:18:25

标签: c++

我有一个程序,用户可以选择将输出保存到文件中。为实现这一目标,我使用freopen

int main(int argc, char* argv[]){   
    if(argc == 1 || argc > 3){
        cerr << "Please specify a SINGLE .txt file to generate word chains from." << endl << "OPTIONAL: specify a log file to store program output. Recommended when processing very large text files." << endl;
        cerr << "Usage: ./PeekClientRMS /path/to/file.txt /path/to/logfile.txt" << endl;
        return 1;
    }

    if(argc == 3){ 
        cout << "Saving output to file " << argv[2] << "."; 
        freopen(argv[2],"w",stdout); 
    }


        // do some stuff here and generate output


    if(argc == 3){ 
        fclose(stdout); 
    }

}

但是,如果我指定一个日志文件,例如/this/clearly/isnt/writable.txt,它会执行而不会抛出错误。是否有ifstream fail()方法可以用来捕获它?

0 个答案:

没有答案