2013-10-16 73 views
0

如果我不知道一个文件是否存在。如果存在,我将根据该文件中的内容做一些事情。该文件可能是.txt或.gz格式,并且该文件也可能不存在。 下面是我的代码:如何检查压缩文件或压缩文件是否存在?

 //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; 
     } 

我要检查具有相同的名称与一个必须的文件例如hello.abc,但我想检查可能是hello.abc或hello.gz的文件的文件甚至不存在。如果我以上述方式执行操作,当文件hello.txt或hello.gz完全不存在时,出现错误。如何解决此问题?

+2

这是C++。为什么它被标记为'C'? –

+0

@JonathonReinhart因为我利用C++和c所以我标记both.or我必须只C++? –

+1

他们是[不同的语言](http://programmers.stackexchange.com/questions/38942/how-is-c-different-from-c)。如果你使用'cout << ...',那么你正在编写C++而不是C. –

回答

2

只要在各种可能的名称上调用fstat()并检查产生的错误(如果有的话)。

+0

你能告诉我一个代码示例吗?如果我想测试abc.gz是否存在? –

+3

['man stat'](http://linux.die.net/man/2/stat) –

0

如果您使用的是POSIX系统(如Linux,BSD或OSX),那么您可以使用stat来查看文件是否存在。在Windows上使用PathFileExists

或使用Boost filesystem库,如其exists函数。

+2

在windows上还有['_stat'](http://msdn.microsoft.com/en-us/library /14h5k7ff.aspx)。 –