VC隐藏文件和判断文件是否存在

来源:互联网 发布:聚橙网络免费吗 编辑:程序博客网 时间:2024/05/14 16:15

一:隐藏文件。 
    1.WinExec函数。 
      该函数执行一个cmd命令,如修改 
      C://Documents and Settings//eMLab//Application Data//test.txt 
      文件属性为隐藏可以: 
      CString strFileName = 
       "C://Documents and Settings//eMLab//Application Data//test.txt"; 
      CString strCmd = "attrib +h" + strFileName; 
      WinExec(strCmd,0); 
      attrib修改文件属性,+h表示给文件加上隐藏属性。 
    2.SetFileAttributes函数 
      原型:BOOL SetFileAttributes(LPCTSTR   lpFileName,   //file name 
                                   WORD   dwFileAttributes //file attribute 
                                  );     
      如: 
      SetFileAttributes(strFileName,FILE_ATTRIBUTE_HIDDEN); 
   FILE_ATTRIBUTE_HIDDEN就表示隐藏属性。  
    3.CFile和CFileStatus类 
      CFile的静态函数GetStatus可以读取文件状态 
      CFile的静态函数SetStatus可以修改文件状态 
      如: 
   FileStatus fs;   
      CFile::GetStatus(strFileName,fs);   
      fs.m_attribute = CFile::hidden;          //set hidden attribute 
      CFile::SetStatus(strFileName,fs);  
二:判断文件是否存在。 
  1.access函数,在io.h中。 
   原型:int access(const char *filename, int amode); 
      参数amode(好象有5种模式) 
      0:检查文件是否存在         
      1:检查文件是否可运行         
      2:检查文件是否可写访问     
      4:检查文件是否可读访问   
      还有一种,由于MSDN突然坏了,暂时保留着 
      if ( access(file,0) ) 
      { 
      //文件不存在 
      } 
    2.CFile和CFileStatus类 
      CFile的静态函数GetStatus如果返回FALSE表示文件不存在 
      CFileStatus fs;   
      if ( !CFile::GetStatus(strFileName,fs) ) 
      { 
       //文件不存在 
      } 

     3.CFileFind类 
       直接使用该类的成员函数FindFile进行判断 
       CFileFind ff;   
       if ( !ff.FindFile(strFileName) )   
       { 
       //文件不存在   
       } 
       ff.Close();

 

 

转自 :

http://hi.bccn.net/space-88329-do-blog-id-12205.html

 

我需要实现文件隐藏和判断文件是否存在,选择用CFile和CFileStatus类实现,感觉有用转来自己学习。

另注:

CFile类需要包含的头文件 #include   <Afx.h>

在MSDN上查找的几个文件的几个类型,把文件影藏了也想想怎么把属性变成其他的。

 

The m_attribute is the file attribute. The Microsoft Foundation classes provide an enum type attribute so that you can specify attributes symbolically:

复制
enum Attribute {   normal =    0x00,x01,   hidden =    0x02,   system =    0x04,   volume =    0x08,   directory = 0x10,   archive =   0x20   };
在获取和修改文件属性的时候也是和文件的一种绑定不能在文件读写的语句还释放文件的时候加CFILE修改文件属性的语句。
记得关闭文件。

 使用CFile::GetStatus获取文件状态的时候遇到一直是判断文件不存在。下面是在网上看到的解释。

 

因为你指定的路径是:c:/myfile.txt
而调用上面大家提出的检查函数的需要的路径参数是需要双斜杠的!
所以:你调用时就出现了运行结果错误。

举例来说:
下面假设你的C:/My   Documents/下存在aa.xl文件。
下面做2种情况下的测试:
1)
CFileStatus   status;
if   (CFile::GetStatus( "C://My   Documents//aa.xls ",status)==TRUE)
AfxMessageBox( "Exists ");
else
AfxMessageBox( "not   Exists ");
运行的结果就是正确的,
2)但是,如果你这样引用:
CFileStatus   status;
if   (CFile::GetStatus( "C:/My   Documents/aa.xls ",status)==TRUE)
AfxMessageBox( "Exists ");
else
AfxMessageBox( "not   Exists ");
这样引用,即使该文件已经存在,程序仍然报该文件不存在。

因此,引用上面的函数,需要进行一个路径转换(变成双斜杠)。

我觉得用PathFileExists函数可以避免转换,并可以解决这个问题

原创粉丝点击