0

If i dont know whether a file is exist.If it exist i will do something depend on the content in that file.The file could be in .txt or .gz format and the file can also not exist. Below is my code:

      //Check whether is a zip file
      char *pre_pcom_file_copy = new char[strlen(pre_pat_file)+7];
      strcpy (pre_pcom_file_copy,pre_pcom_file);
      strcat (pre_pcom_file_copy,".gz");
      char *cmd = new char[strlen("gzip -dc ")+strlen(pre_pcom_file_copy)+1];
      strcpy (cmd,"gzip -dc ");
      strcat (cmd,pre_pcom_file_copy);
      if ( (pre_pcom = popen(cmd,"r")) == NULL ){
          //Do nothing
      }else{
          cout << "Parsing pre.pcomments file   --->" << pre_pcom_file << endl;
          pcomyyin = pre_pcom;
          if(_vecTime.size() > 0){
              //for pre_pcom _vecTime should be empty
              pcom_time = _vecTime[_vecTime.size()-1];
          }
          first_time = 1; // make sure tester cycle start from 0 from pcomment file
          pcomyyparse ();
          pclose(pre_pcom);
          //delete [] cmd;
          cout << "Parsing pre.pcomments file DONE!" << endl;
      }

I want to check a file that has the same name with a must have file for example hello.abc but the file i want to check could be hello.abc or hello.gz or even not exist.If i do in the way like above i got error when the file hello.txt or hello.gz are totally not exist.How can i solve this?

user207421
  • 305,947
  • 44
  • 307
  • 483
Jaden Ng
  • 141
  • 1
  • 12

2 Answers2

2

Just call fstat() on the various possible names and check the resulting error if any.

user207421
  • 305,947
  • 44
  • 307
  • 483
0

If you're on a POSIX system (like Linux, BSD or OSX) then you can use stat to see if a file exists. On Windows use PathFileExists.

Or use the Boost filesystem library, like its exists function.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621