从文本文件中读取行,转换它们,然后写回新文件

本文关键字:文件 然后 写回 新文件 转换 文本 读取 | 更新日期: 2023-09-27 18:04:40

我对c#有一些基本的了解,但是我在编码一些概念上看起来很简单的东西时遇到了麻烦。我想读取一个包含

等值的文件(.asm)
@1
@12
@96
@2
@46
etc.

在多个连续行上。然后我想去掉@符号(如果它们存在的话),将剩下的数字值转换为二进制,然后将这些二进制值写回一个新的文件(.hack)。对行数没有设置限制,这是我最大的问题,因为我不知道如何动态检查行。到目前为止,我只能读取和转换行,如果我编写代码来查找它们,那么我无法弄清楚如何在新文件中自己的行中编写这些值。抱歉,如果这听起来有点复杂,但任何帮助将不胜感激。谢谢!

if (openFileDialog1.ShowDialog() == DialogResult.OK)
        {
            var line = File.ReadAllText(openFileDialog1.FileName);
            using (StreamWriter sw = File.CreateText("testCode.hack"))
            {
                var str = line;
                var charsToRemove = new string[] {"@"};
                foreach (var c in charsToRemove)
                {
                    str = str.Replace(c, string.Empty);
                }
                int value = Convert.ToInt32(str);
                string value2 = Convert.ToString(value, 2);
                if (value2.Length < 16)
                {
                    int zeroes = 16 - value2.Length;
                    if(zeroes == 12)
                    {
                        sw.WriteLine("000000000000" + value2);
                    }
                }
                else
                {
                    sw.WriteLine(value2);
                }
            }

从文本文件中读取行,转换它们,然后写回新文件

这段代码应该可以帮助您快速运行:

static void Main(string[] args)
    {
        string line = string.Empty;
        System.IO.StreamReader reader = new System.IO.StreamReader(@"C:'test.txt");
        System.IO.StreamWriter writer = new System.IO.StreamWriter(@"C:'test.hack");
        while ((line = reader.ReadLine()) != null) // Read until there is nothing more to read
        {
            if (line.StartsWith("@"))
            {
                line = line.Remove(0, 1); // Remove '@'
            }
            int value = -1;
            if (Int32.TryParse(line, out value)) // Check if the rest string is an integer
            {
                // Convert the rest string to its binary representation and write it to the file
                writer.WriteLine(intToBinary(value));
            }
            else
            {
                // Couldn't convert the string to an integer..
            }
        }
        reader.Close();
        writer.Close();
        Console.WriteLine("Done!");
        Console.Read();
    }
    //http://www.dotnetperls.com/binary-representation
    static string intToBinary(int n)
    {
        char[] b = new char[32];
        int pos = 31;
        int i = 0;
        while (i < 32)
        {
            if ((n & (1 << i)) != 0)
            {
                b[pos] = '1';
            }
            else
            {
                b[pos] = '0';
            }
            pos--;
            i++;
        }
        return new string(b);
    }

我建议创建一个List<string>。以下是步骤

  1. 读取输入(.asm)文件到List
  2. 打开StreamWriter输出(.hack)文件。
  3. 通过List<string>循环修改字符串并写入文件

代码示例:

 List<string> lstInput = new List<string>();     
 using (StreamReader reader = new StreamReader(@"input.asm"))
 {
    string sLine = string.Empty;
    //read one line at a time
    while ((sLine = reader.ReadLine()) != null)
    {
        lstInput.Add(sLine);
    }
 }
 using (StreamWriter writer =  new StreamWriter(@"output.hack"))
 {
       foreach(string sFullLine in lstInput)
       {
           string sNumber = sFullLine;
           //remove leading @ sign
           if(sFullLine.StartsWith("@"))               
              sNumber = sFullLine.Substring(1);
           int iNumber;
           if(int.TryParse(sNumber, out iNumber))
           {    
              writer.WriteLine(IntToBinaryString(iNumber));
           }
       }
 }

 public string IntToBinaryString(int number)
 {
     const int mask = 1;
     var binary = string.Empty;
     while(number > 0)
     {
         // Logical AND the number and prepend it to the result string
         binary = (number & 1) + binary;
         number = number >> 1;
     }
     return binary;
 }

参考:IntToBinaryString方法

注意: @TheDutchMan回答中提到的Int to Binary String方法是更好的选择