C++ 文件删除注释

读取一个cpp文件,删除里面的所有注释,生成一个新的cpp文件。

在这里我用的是一行一行地读取,写的稍微有点复杂,将单行注释与多行注释分开来写了。实际上可以一个一个读取。

思路就是判断是不是注释里面的内容,若不是,则写入新文件。

#include <iostream>
#include <fstream>
#include <Windows.h>
#include <tchar.h>
using namespace std;

bool deleteSingle(const char*, const char *);
void deleteMulti(const char *, const char *);
bool deleteAll(const char *, const char *);

int main()
{
	deleteAll("ConsoleApplication45.cpp", "test.cpp");
}

bool deleteSingle(const char * oldFileSrc, const char * newFileSrc)
{
	fstream oldfile(oldFileSrc, ios::in);
	fstream newfile(newFileSrc, ios::out);
	if (oldfile.is_open() && newfile.is_open())
	{
		const int size = 250;   //设定每行的缓存大小
		char temp[size];
		oldfile.seekg(0, ios::beg);   //指针移向文件头
		while (oldfile.getline(temp, size)) //逐行读取,遇单行注释则终止
		{
			for (int i = 0; i < size; i++)
			{
				if (temp[i] == '/'&&temp[i + 1] == '/')
				{
					temp[i] = 0;
				}
			}
			newfile << temp << endl;
		}
		oldfile.close();
		newfile.close();
		return true;
		/*删除单行注释成功*/
	}
	else
	{
		cout << "源文件无法打开或无法创建新文件,请重试!\n";
		return false;
	}
}
void deleteMulti(const char * oldFileSrc, const char * newFileSrc)
{
	fstream oldfile(oldFileSrc, ios::in);
	fstream newfile(newFileSrc, ios::out);
	if (oldfile.is_open() && newfile.is_open())
	{
		const int size = 250;
		char temp[size];
		bool meetFlag = false;    //是否遇到了多行注释的标记
		oldfile.seekg(0, ios::beg);
		while (oldfile.getline(temp, size))
		{
			int i;
			for (i = 0; i < size - 1; i++)
			{
				if (temp[i] == '\n') break;
				/*
					没遇见标记前,检测标记
				*/
				if (!meetFlag && temp[i] == '/' && temp[i + 1] == '*')
				{
					temp[i] = 0;
					meetFlag = !meetFlag;   //遇见了标记,故重置标记
				}
				if (temp[i] == '*' && temp[i + 1] == '/')  //找到了标记的结束位置
				{
					meetFlag = !meetFlag;  //重置标记
					int j, k;
					for (j = i + 2, k = 0; j < size; j++)   //写入结束标记后的文字
					{
						if (temp[j] == '\n')  break;
						temp[k++] = temp[j];
					}
					temp[--j] = 0;
				}
			}
			if (!meetFlag) //在注释标记间的文字不写入
			{
				newfile << temp << endl;
			}
		}
		oldfile.close();
		newfile.close();
	}
}

bool deleteAll(const char *oldFileSrc, const char *newFileSrc)
{
	bool success = deleteSingle(oldFileSrc, "temp.cpp");
	if (success)
	{
		deleteMulti("temp.cpp", newFileSrc);
		DeleteFile(_T("temp.cpp"));   //删除缓存文件
		return true;
	}
	DeleteFile(_T("temp.cpp"));
	return false;
}

猜你喜欢

转载自blog.csdn.net/weixin_43894577/article/details/89430355
今日推荐