C Fiile Writer不会写我给它的字符

C++ fiile writer does not write characters that I give it

本文关键字:字符 Fiile Writer      更新时间:2023-10-16

我目前正在为我的计算机组织课程开展一个项目,我的教授决定将我们投入到一个C 项目中,没有任何上课时间或经验。该项目的目的是创建一个可以使用运行长度编码来压缩或解压缩文件的程序,并为我们提供了一个代码框架。我目前正在尝试编写编码函数,这就是我到目前为止所拥有的。请记住,我在C或C 上绝对没有经验。

void compress( char* data, int count, FILE* outfile )
{
// TODO: compress the data instead of just writing it out to the file
char currentChar = data[0];
int charCount;
charCount = 0;
for (int i=0; i<count; ++i)
{
   if(data[i] == currentChar)
   {
       charCount++;
   }
   else if(data[i] != currentChar)
   {
      if(charCount > 9)
      {
           while(charCount > 9)
           {
               putc(currentChar, outfile); // write the current char to the file
               putc(9, outfile); // write 9 to the file
               charCount -= 9;
           }
           putc( currentChar, outfile ); // write the current char to the file
           putc( charCount, outfile); // write the number of currentChar to the file
       }
       else
       {
           putc( currentChar, outfile ); // write the current char to the file
           putc( charCount, outfile); // write the number of currentChar to the file
       }
       // reset the currentChar and charCount variables
       currentChar = data[i];
       charCount = 1;
      }
   }
}

该代码给出的输出如下:x x(未知字符)y(未知字符)

应该是:x9x1y4z3

我到底在做什么错?就我(极有限)的知识而言,这应该是正确的。但同样,我是C 的新手(我唯一的其他编码体验是在Python和Java中)。

编辑:好,数字编写正确。现在输出为:x9x1y4,几乎是正确的。现在,bot的压缩代码仍在忽略测试文件末尾的三个z。我会通过内置的Eclipse内置的调试套件来运行它,但是由于某种原因,它说在我以调试模式运行时不存在测试文件。

关于3 z的未计数:您的代码仅在处理字符时输出数据。在所有字符都由您的for循环处理后,您需要再次转储CurrentChar和Charcount。

如果要将一个数字写入文件,您可以做

之类的事情
putc (charCount + 48, fp)

这仅适用于整数0-9。对于较大的数字,您需要获取每个数字并向其添加48个。

尽管从查看您的代码来看,Charcount变量将始终为1。我认为代码的最后一行可能是

charCount += 1

另一个选项是:

putc('0' + charCount, outfile);

putc('0' + 9, outfile);