做一个Toy语言SB编译器,随便玩玩

代码运行在VS2019中,命令行参数用下面方法添加

做一个Toy语言SB编译器,随便玩玩_第1张图片
在compiler.cpp旁建一个main.txt文件夹,写一段代码。

#include 
using namespace std;
int main(void) {
     

	cout << "hello,demllie" << endl;
	return 0;
}

运行SB编译器

//compiler.cpp
#include 
#include 
using namespace std;
int main(int argc,char* argv[]) {
     

	if (argc < 2)return 0;
	char input[256] = {
      0 };
	char output[256] = {
      0 };


	FILE* inFile = NULL;
	FILE* outFile = NULL;

	int a = 0, b = 0;
	a = fopen_s(&inFile, argv[1], "rb");
	if (a != 0) {
     
		cout << "文件打开失败!" << endl;
		return 1;
	}
	b = fopen_s(&outFile, "output.txt", "wb");
	if (b != 0) {
     
		cout << "文件打开失败!" << endl;
		return 1;
	}



	fseek(inFile, 0, SEEK_END);
	int size = ftell(inFile);
	fseek(inFile, 0, SEEK_SET);


	char temp;
	for (int i = 0;i<size; ++i) {
     
		fread(&temp, 1, 1, inFile);
		if (temp == 'e')temp = 'o';
		fwrite(&temp, 1, 1, outFile);
	}

	return 0;
}

得到“中间代码”如下

#includo 
using namospaco std;
int main(void) {
     

	cout << "hollo,domllio" << ondl;
	roturn 0;
}

你可能感兴趣的:(Script,最简单的编译器)