file.h

来自「一个可视化的编译器」· C头文件 代码 · 共 129 行

H
129
字号
/// <author> 任晶磊 </author>
/// <update> 2008-3-1 </update>
///	<E-mail> renjinglei@163.com </E-mail>

#ifndef FILE_H
#define FILE_H

#include <fstream>
#include <string>
#include <exception>

namespace FileAdapter
{
	using namespace std;

	class File
	{
		string fileName;
		int lineNum;
		int charNum;
		///<summary>用于记录当前行的上一行字符数,回退到上一行时使用</summary>
		int charNumLastLine;
		fstream file;
	public:
		File():lineNum(1), charNum(1){}
		
		File(string name):fileName(name), lineNum(1), charNum(1)
		{
			file.open(fileName.c_str());
			if (!file) throw FileOpenFailure();
		}

		void Open(string name)
		{
			fileName = name;
			file.open(fileName.c_str());
			if (!file) throw FileOpenFailure();
		}

		void Close()
		{
			file.close();
		}

		string& GetName()
		{
			return fileName;
		}

		char Get()
		{
			char next = file.get();
			if (next == '\n')
			{
				++lineNum;
				charNumLastLine = charNum;
				charNum = 1;
			}
			else ++charNum;
			return next;
		}

		void Ignore()
		{
			Get();
		}

		char Peek()
		{
			return file.peek();
		}

		void PutBack(char next)
		{
			if (next == '\n')
			{
				--lineNum;
				charNum = charNumLastLine;
			}
			else
			{
				--charNum;
			}
			file.putback(next);
		}

		int GetLineNum()
		{
			return lineNum;
		}

		int GetCharNum()
		{
			return charNum;
		}

		string GetLine()
		{
			string line;
			getline(file, line);
			return line;
		}

		bool Eof()
		{
			return file.eof();
		}

		void Reset()
		{
			file.clear();
			file.seekg(ios::beg);
		}

		/// <summary>
		/// 文件打开异常
		/// </summary>
		class FileOpenFailure : public std::exception
		{
		public:
			virtual const char* what() const throw()
			{
				return "文件打开失败!";
			}
		};
	};
}

#endif

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?