在软件设计中,对文件系统的利用往往是必不可少的,它能帮助我们存储许多比较重要的数据,保存过程数据和备份数据,以备软件出现不可预知的偶然异常时,恢复测试数据和测试过程使用。
下面结合实例来讲述文件相关的一些操作(完整的实例程序可在我的CSDN资源中下载:http://download.csdn.net/detail/margin1988/4239839):
(1)创建目录(文件夹):
1)方法1:
1 CString strDir; 2 strDir.Format("%sdir1",g_BasePath); 3 ::CreateDirectory(_T(strDir),NULL);
2)方法2:
1 #include <direct.h> 2 strDir.Format("%sdir2",g_BasePath); 3 _mkdir(strDir);
(2)创建及写文件(不追加模式、追加模式):
1)不追加模式:
1 CStdioFile file; 2 CString str; 3 str.Format("%sdir1\\data1.txt",g_BasePath); 4 if (!file.Open(_T(str),CFile::modeCreate |CFile::modeWrite | CFile::typeText)) 5 { 6 MessageBox(_T("未打开文件")); 7 } 8 else 9 { 10 for (int i=1;i<11;i++) 11 { 12 str.Format("%d-%d\n",i,i*i); 13 file.WriteString(str); 14 } 15 file.Close(); 16 }
2)追加模式:
1 CStdioFile file; 2 CString str; 3 str.Format("%sdir1\\data2.txt",g_BasePath); 4 if (!file.Open(_T(str),CFile::modeCreate |CFile::modeWrite | CFile::typeText | CFile::modeNoTruncate)) 5 { 6 MessageBox(_T("未打开文件")); 7 } 8 else 9 { 10 for (int i=1;i<11;i++) 11 { 12 str.Format("%d\n",i); 13 file.SeekToEnd();//定位至文件末尾 14 file.WriteString(str); 15 } 16 file.Close(); 17 }
(3)读文件:
1 CStdioFile file; 2 CString str,str1,str2; 3 str.Format("%sdir1\\data1.txt",g_BasePath); 4 if (file.Open(_T(str),CFile::modeRead |CFile::typeText)) 5 { 6 file.SeekToBegin();//定位到文件开头 7 while(file.ReadString(str))//读取文件中的一行 8 { 9 if(AfxExtractSubString(str1,str,0,'-'))//截取字符串 10 { 11 if(AfxExtractSubString(str2,str,1,'-')) 12 { 13 MessageBox(str1+"的平方="+str2); 14 } 15 } 16 } 17 file.Close(); 18 } 19 else 20 MessageBox(_T("data1.txt文件打开失败"));
(4)计算文件行数:
1 CStdioFile file; 2 CString str; 3 str.Format("%sdir1\\data2.txt",g_BasePath); 4 int lineNum=0;//统计文件行数的变量 5 if (file.Open(_T(str),CFile::modeRead |CFile::typeText)) 6 { 7 file.SeekToBegin();//定位到文件开头 8 while (file.ReadString(str)) //读取文件中的一行 9 { 10 lineNum++; 11 } 12 file.Close();//关闭文件 13 str.Format("data2.txt共计%d 行",lineNum); 14 MessageBox(str); 15 } 16 else 17 MessageBox(_T("data2.txt文件打开失败"));
(5)计算目录下文件个数:
1 //SDK方式统计指定目录下的文件个数 2 HANDLE hFind; 3 WIN32_FIND_DATA dataFind; 4 BOOL bMoreFiles=TRUE; 5 int iCount=0;//统计文件数的变量 6 CString str; 7 str.Format("%sdir1\\",g_BasePath);//str是指定的路径 8 hFind=FindFirstFile(str+"*.*",&dataFind);//找到路径中所有文件 9 //遍历路径中所有文件 10 while(hFind!=INVALID_HANDLE_VALUE&&bMoreFiles==TRUE) 11 { if(dataFind.dwFileAttributes!=FILE_ATTRIBUTE_DIRECTORY)//判断是否是文件 12 { 13 iCount++; 14 } 15 bMoreFiles=FindNextFile(hFind,&dataFind); 16 } 17 FindClose(hFind); 18 str.Format("dir1目录下文件个数共计%d 个",iCount); 19 MessageBox(str);
(6)删除文件:
1 CFileFind finder; 2 CString str; 3 str.Format("%sdir1\\data1.txt",g_BasePath); 4 if (finder.FindFile(_T(str))) 5 { 6 ::DeleteFile(_T(str)); 7 }
(7)删除目录:
RemoveDirectory和_rmdir两者都只能删除空文件夹,若要删其下有文件的文件夹,需先删除其下的所有文件,再删除文件夹。
1)方法1:
1 CString strDir; 2 strDir.Format("%sdir2",g_BasePath); 3 ::RemoveDirectory(strDir);
2)方法2:
1 #include <direct.h> 2 strDir.Format("%sdir1",g_BasePath); 3 _rmdir(strDir);