Simpletron com processamento de arquivos. No Exercício 7.19, você escreveu uma simulação de software de um computador que usava uma linguagem de máquina especial, chamada Simpletron Machine Language (SML). Na simulação, toda vez que você queria executar um programa SML, entrava com o programa no simulador por meio do teclado. Se você cometesse um erro durante a digitação do programa SML, o simulador era reiniciado e o código SML era reinserido. Seria bom ler o programa SML de um arquivo em vez de ter de digitá-lo várias vezes. Isso reduziria o tempo e os erros na preparação da execução dos programas SML.

a) Modifique o simulador que você escreveu no Exercício

7.19 para que seja possível ler os programas

SML a partir de um arquivo especificado pelo usuário

no teclado.

b) Após a execução do Simpletron, ele mostra o conteúdo

de seus registradores e da memória na tela. Seria

bom capturar a saída em um arquivo; portanto, modifique

o simulador para que ele grave sua saída em

um arquivo, além de exibi-la na tela.

Passo 1

Precisamos adicionar 2 funções à nossa máquina Simpletron:

simpletronLoadFromFile() que irá:

Leia o nome do arquivo no console.

Abra o arquivo e leia até chegar ao final do arquivo.

Leia o endereço, o sinal da palavra e a palavra e armazene-os na memória.

Quando a palavra -99999 for lida, pare a leitura.

simpletronPrintMemory() que irá:

Atravesse a memória.

Imprima cada uma das palavras e seus endereços em formato tabular no arquivo e no console.

Simpletron.c

#include

#include

#define READ 10

#define WRITE 11

#define LOAD 20

#define STORE 21

#define ADD 30

#define SUBTRACT 31

#define DIVIDE 32

#define MULTIPLY 33

#define BRANCH 40

#define BRANCHNEG 41

#define BRANCHZERO 42

#define HALT 43

int memory[100];

void simpletronGreet() {

printf("*** Welcome to Simpletron! ***\n***Please enter your program one instruction ***\n***(or data word) at a time.I will type the ***\n***location number and a question mark(? ). ***\n***You then type the word for that location.****** Type the sentinel - 99999 to stop entering ***\n***your program. ***\n");

}

void simpletronLoad() {

int lastAddress = 0;

int address = 0;

int word = 0;

char sign = '+';

int read = 1;

while (read) {

do {

scanf("%d ? %c%d", &address, &sign, &word);

if ((word > 10000 || word

}

while ((word > 10000 || word

if (sign == '-') word *= -1;

if (address > lastAddress) lastAddress = address;

if (word-10000) {

memory[address] = word;

}

else if(word == -99999){

read = 0;

memory[lastAddress] = HALT*100;

}

else {

printf("Error\n");

}

}

}

int simpletronLoadFromFile() {

char filename[20];

scanf("%s", filename);

FILE* f = fopen(filename, "r");

int lastAddress = 0;

char read[10];

int address;

char sign;

int word;

if (f != NULL) {

while (!feof(f)) {

fscanf(f, "%d ? %c%d", &address, &sign, &word);

if (sign == '-') word *= -1;

if (address > lastAddress) lastAddress = address;

if (word-10000) {

memory[address] = word;

}

else if (word == -99999) {

memory[lastAddress] = HALT * 100;

}

else {

printf("Error\n");

return 1;

}

}

fclose(f);

}

else return 1;

return 0;

}

void simpletronPrintMemory() {

FILE* f = fopen("result.txt", "w");

if (f != NULL) {

printf("%-9s %-9s %-9s %-9s %-9s %-9s %-9s %-9s %-9s %-9s %-9s\n", "", "00", "01", "02", "03", "04", "05", "06", "07", "08", "09");

fprintf(f,"%-9s %-9s %-9s %-9s %-9s %-9s %-9s %-9s %-9s %-9s %-9s\n", "", "00", "01", "02", "03", "04", "05", "06", "07", "08", "09");

for (int i = 0; i

printf("%-10d", i);

fprintf(f,"%-10d", i);

for (int j = 0; j

int read = memory[i + j];

printf("%-+10.4d", read);

fprintf(f,"%-+10.4d", read);

}

printf("\n");

fprintf(f,"\n");

}

fclose(f);

}

else return 1;

return 0;

}

int main()

{

simpletronGreet();

simpletronLoadFromFile();

int instruction = 0;

int operation = READ;

int operandPointer = 0;

int read = 0;

int accumulator = 0;

int programCounter = 0;

int execute = 1;

while (programCounter

instruction = memory[programCounter];

operation = instruction / 100;

operandPointer = instruction % 100;

switch (operation) {

case READ:

scanf("%d", &read);

memory[operandPointer] = read;

break;

case WRITE:

printf("%d\n", memory[operandPointer]);

break;

case LOAD:

accumulator = memory[operandPointer];

break;

case STORE:

memory[operandPointer]=accumulator;

break;

case ADD:

accumulator += memory[operandPointer];

break;

case SUBTRACT:

accumulator -= memory[operandPointer];

break;

case DIVIDE:

accumulator /= memory[operandPointer];

break;

case MULTIPLY:

accumulator *= memory[operandPointer];

break;

case BRANCH:

programCounter=operandPointer;

break;

case BRANCHNEG:

if(accumulator

break;

case BRANCHZERO:

if (accumulator == 0) programCounter = operandPointer;

break;

case HALT:

execute = 0;

break;

}

programCounter++;

}

simpletronPrintMemory();

}

Passo 2

Agora vamos testar o programa com o arquivo test.txt que contém:

00? +1007

01? +1008

02? +2007

03? +3008

04? +2109

05? +1109

06? +4300

07? +0000

08? +0000

09? +0000

10? -99999

A entrada no console será:

test.txt

20

8

Passo 3

Modifique o programa que simula a máquina simplória adicionando funções para ler instruções de um arquivo de texto e imprimir a memória em um arquivo diferente.

Resposta

Ver o desenvolvimento.