1

对于家庭作业,我必须为 MIPS 代码创建一个非常简化的汇编程序。所以我们接受一个 MIPS 指令的输入文件,然后输出一个包含输入代码相关二进制文件的文件。每行代码都必须映射到一个“内存”位置,该位置只是行前的一个十六进制值,但我们添加/分配这个“内存”。

因此,我想做的是从文本文件的每一行中读取,并且在前面我想附加一个值(十六进制的起始内存地址+(行号* 4)。然后我想重新读取文件。如果我需要读取整个文件,请创建一个分配了内存的新文件,然后读取该文件,这很好,但我想可能是不必要的。

我们的教授建议了一份清单,所以这是我目前所拥有的:

Console.WriteLine("Please enter the path to the input file:");
string inp = Console.ReadLine();
Console.WriteLine("Please enter the name of the new file:");
string otp = Console.ReadLine();
StreamReader inputFile = new StreamReader(inp);
StreamWriter outputFile = new StreamWriter(otp);
List<string> fileContents = new List<string>();
while ((inp = inputFile.ReadLine()) != null)
     fileContents.Add(inp);

所以我的问题是:如何在该列表(fileContents)中每个项目的开头添加一个字符串?

编辑: 对此的跟进:到目前为止,我已经设法完成所有这些工作,我已经引入了整个文档,将内存位置映射到每一行等。但是,我需要进一步编辑其中的一些行通过从其中删除一些信息来列出“inputLines”。

格式将始终为 [0] 内存地址 [1] 标签,或者,如果此行中没有标签,则为寄存器、操作等 [2]-[?] 寄存器、操作等。一旦我将内存映射到每一行,任何具有标签的行,我都想将其放入字典中,索引作为标签,内存地址作为包含的值,然后去掉标签。那么 - 我如何从包含它的任何行中删除该信息?

//go through each line, if any line's first "token" is a label, 
//put it in the dictionary as the index with the memory address as the value
//delete the label from the line
for (int i = 0; i < inputLines.Length; i++)
    {
       string[] token = inputLines[i].Split(new char[] { ' ', ',', '(', ')', ':' }, StringSplitOptions.RemoveEmptyEntries);
            string possibleLabel = token[1];
            if (opcodes.ContainsKey(possibleLabel) == false)
            {
                labeltable.Add(possibleLabel, token[0]);
                //at this point I want to delete the possibleLabel from the inputLines[i] and not deal with it anymore.
            }

        }

那确实正确映射到我的字典,所以不用担心那部分。

4

3 回答 3

0
var inputLines = File.ReadAllLines(inputFilePath);
for (int i=0; i<inputLines.Length; i++)
    inputLines[i] = "Some Text" + inputLines[i];
于 2013-04-19T07:07:03.993 回答
0

假设您的前缀在另一个列表中

var prefixes = new List<string>(/* som values */);

var ix = 0;

var result = fileContents.Select(x => string.Join(" ", prefixes[ix++], x)).ToArray();

如果您需要加入行号(来自字典)

var prefixes = new Dictionary<int, string>(); // Needs values

var result = new List<string>();

for (var i = 0; i < fileContents.Count; i++){
   string prefix;

   if (prefixes.TryGetValue(i, out prefix){ result.Add(string.Join(" ", prefix, fileContent[i])) }
   else { result.Add(fileContent[i]);}
}
于 2013-04-19T07:10:22.223 回答
0

您可以使用 StringBuilder 作为 Faisal 代码的优化,否则它非常适合您的需求

Console.WriteLine("Please enter the path to the input file:");
string inp = Console.ReadLine();
Console.WriteLine("Please enter the name of the new file:");
string otp = Console.ReadLine();

System.Text.StringBuilder sb = new System.Text.StringBuilder();
string inputLines = System.IO.File.ReadAllLines(inp);
 for (int i = 0; i < inputLines.Length; i++)
     sb.Append("Some Text" + inputLines[i] + Environment.NewLine);

File.WriteAllText(otp, sb.ToString())
于 2013-04-19T07:19:32.420 回答