VC++中文件读、写和其他相关操作汇总

在软件设计中,对文件系统的利用往往是必不可少的,它能帮助我们存储许多比较重要的数据,保存过程数据和备份数据,以备软件出现不可预知的偶然异常时,恢复测试数据和测试过程使用。

下面结合实例来讲述文件相关的一些操作(完整的实例程序可在我的CSDN资源中下载:http://download.csdn.net/detail/margin1988/4239839):

(1)创建目录(文件夹):

 1)方法1:

CString strDir;
strDir.Format("%sdir1",g_BasePath);
::CreateDirectory(_T(strDir),NULL);

2)方法2:

#include <direct.h>
strDir.Format("%sdir2",g_BasePath);
_mkdir(strDir);

(2)创建及写文件(不追加模式、追加模式):

1)不追加模式:

CStdioFile file;
CString str;
str.Format("%sdir1data1.txt",g_BasePath);
if (!file.Open(_T(str),CFile::modeCreate | CFile::modeWrite | CFile::typeText))
{
   MessageBox(_T("未打开文件"));
}
else
{
   for (int i=1;i<11;i++)
   {
      str.Format("%d-%d
",i,i*i);
      file.WriteString(str);
   }
   file.Close();
}

 2)追加模式:

CStdioFile file;
CString str;
str.Format("%sdir1data2.txt",g_BasePath);
if (!file.Open(_T(str),CFile::modeCreate | CFile::modeWrite | CFile::typeText | CFile::modeNoTruncate))
{
   MessageBox(_T("未打开文件"));
}
else
{
   for (int i=1;i<11;i++)
   {
      str.Format("%d
",i);
      file.SeekToEnd();//定位至文件末尾
      file.WriteString(str);
   }
   file.Close();
}

(3)读文件:

CStdioFile file;
CString str,str1,str2;
str.Format("%sdir1data1.txt",g_BasePath);
if (file.Open(_T(str),CFile::modeRead | CFile::typeText))
{
   file.SeekToBegin();//定位到文件开头
   while(file.ReadString(str))//读取文件中的一行
   {
      if(AfxExtractSubString(str1,str,0,"-"))//截取字符串
      {
         if(AfxExtractSubString(str2,str,1,"-"))
         {
            MessageBox(str1+"的平方="+str2);
         }
      }
   }
   file.Close();
}
else
   MessageBox(_T("data1.txt文件打开失败"));

(4)计算文件行数:

CStdioFile file;
CString str;
str.Format("%sdir1data2.txt",g_BasePath);
int lineNum=0;//统计文件行数的变量
if (file.Open(_T(str),CFile::modeRead | CFile::typeText))
{
   file.SeekToBegin();//定位到文件开头
   while (file.ReadString(str)) //读取文件中的一行
   {
      lineNum++;
   }
   file.Close();//关闭文件
   str.Format("data2.txt共计%d 行",lineNum);
   MessageBox(str);
}
else
   MessageBox(_T("data2.txt文件打开失败"));

(5)计算目录下文件个数:

//SDK方式统计指定目录下的文件个数
HANDLE hFind; 
WIN32_FIND_DATA dataFind; 
BOOL bMoreFiles=TRUE; 
int iCount=0;//统计文件数的变量
CString str;
str.Format("%sdir1",g_BasePath);//str是指定的路径
hFind=FindFirstFile(str+"*.*",&dataFind);//找到路径中所有文件
//遍历路径中所有文件
while(hFind!=INVALID_HANDLE_VALUE&&bMoreFiles==TRUE) 
{ 
   if(dataFind.dwFileAttributes!=FILE_ATTRIBUTE_DIRECTORY)//判断是否是文件
   { 
      iCount++; 
   } 
   bMoreFiles=FindNextFile(hFind,&dataFind); 
} 
FindClose(hFind);
str.Format("dir1目录下文件个数共计%d 个",iCount);
MessageBox(str);

(6)删除文件:

CFileFind finder;
CString str;
str.Format("%sdir1data1.txt",g_BasePath);
if (finder.FindFile(_T(str)))
{
   ::DeleteFile(_T(str));
}

(7)删除目录:

  RemoveDirectory和_rmdir两者都只能删除空文件夹,若要删其下有文件的文件夹,需先删除其下的所有文件,再删除文件夹。

 1)方法1:

CString strDir;
strDir.Format("%sdir2",g_BasePath);
::RemoveDirectory(strDir);

 2)方法2:

#include <direct.h>
strDir.Format("%sdir1",g_BasePath);
_rmdir(strDir);
文章导航