现在的位置: 首页 > 综合 > 正文

VC编程实现:删除一个文本文件中的空行

2013年09月04日 ⁄ 综合 ⁄ 共 826字 ⁄ 字号 评论关闭

文本文件中的空白行,可能是一个空字符串;也可能是空格、制表符组成的空白行,删除时要注意!

//
// 统计一个字符串是否全部是白字符 (0x09–0x0D 或者 0x20)组成
//
bool IsAllSpace(CString &str)
{
	int len = str.GetLength();
	int k = 0;
	bool bAllSpace = true;
	for (int i=0; i<str.GetLength(); i++)
	{
		if (isspace(str[i]))
			k++;
	}

	if(k == len)
		return true;
	else 
		return false; 

}

//
// 打开含有空行的文件,处理完毕保存
//
void CTestDlg::OnButton1() 
{
	CStdioFile fpIn, fpOut;
	if( fpIn.Open("TestIn.c", CFile::typeText ) )
	{
		CString strLine;
		CStringArray arry;
		
		//遍历输入文件每一行
		while(fpIn.ReadString(strLine))
		{
			if (strLine.IsEmpty())
			{
				//如果是空行,跳过!
			}
			else if(IsAllSpace(strLine))
			{
				//如果该行全部是白字符,跳过!
			}
			else
			{
				//剩下的,该行有内容,保存!
				arry.Add(strLine);
			}
		}


		//保存到文件中
		if (fpOut.Open("TestOut.c", CFile::modeCreate| CFile::modeWrite | CFile::typeText ))
		{
			for (int i=0; i<arry.GetSize(); i++)
			{
				fpOut.WriteString(arry[i]);
				fpOut.WriteString("\n");
			}
			fpOut.Close();
		}
		else
		{
			AfxMessageBox("输出文件未找到");
		}

		fpIn.Close();
	}
	else
	{
		AfxMessageBox("输入文件未找到");
	}

}

抱歉!评论已关闭.