Posted By

trentonknight on 09/05/10


Tagged

ifstream


Versions (?)

Check File exists


 / Published in: C++
 

Just a lazy way to verify file exists before reading from another function. It may not be the best so feel free to comment on better ways. Just create a string in function you are calling from or main and do this:

string getData, file; ifstream inData; file = checkFileExists(); inData.open(file.c_str()); inData >> getData;

  1. string checkFileExists(){
  2. string file;
  3. ifstream inputFile;
  4.  
  5. cout << "Enter file name: " << endl;
  6. cin >> file;
  7.  
  8. inputFile.open(file.c_str());
  9. if(inputFile){
  10. return file;
  11. }
  12. else{
  13. cout << "ERROR: not found!" << endl;
  14. file.clear();
  15. file = checkFileExists();
  16. }
  17. inputFile.close();
  18. inputFile.clear();
  19. }

Report this snippet  

You need to login to post a comment.