C程序读取输入文件并输出" \ n"新行每50个字符

时间:2015-04-14 18:18:22

标签: c

void filecopy(FILE *ifp, FILE *ofp)
{
  int c;

  while((c = getc(ifp))!= EOF)
    putc(c,ofp);
}

所以,我试过了:

void filecopy(FILE *ifp, FILE *ofp)
{
  int c;
  int count = 0;

  while((c = getc(ifp))!= EOF)
    if(count == 50){
     putc("\n",ofp);//This didnt work
     count = 0;
     }
    putc(c,ofp);
}

我应该使用某种类型的指针吗?我对C指针不太好,有人知道吗?谢谢。

4 个答案:

答案 0 :(得分:2)

你的putc正在尝试输出一个字符串,实际上是一个指针。 putc只是将最初的8位作为变量的char,在这种情况下肯定不是\n

你可能想要(注意单引号):

putc('\n', ofp);

如果您使用的是Windows,则可能需要输出\r\n才能获得所需的结果。

最后,你的循环没有测试每50个字符,它在每次循环迭代时输出值。我认为你已经做了这个测试。

答案 1 :(得分:2)

几个问题:

  1. 您的while循环需要大括号
  2. '\n'不是"\n"
  3. 增量count
  4. 您的最终代码应如下所示:

    void filecopy(FILE *ifp, FILE *ofp)
    {
      int c;
      int count = 0;
    
      while((c = getc(ifp))!= EOF){
        if(count == 50){
          putc('\n',ofp);//This didnt work
          count = 0;
        }
        putc(c,ofp);
        count++;
      }
    }
    

答案 2 :(得分:0)

基于@Paul的正确答案,您可以使用模数来决定何时输出换行符:

if(++count % 50 == 0){
    putc('\n', ofp);
}

答案 3 :(得分:0)

答案是:

void filecopy(FILE *ifp, FILE *ofp)
{
  int c;
  int count = 0;

  while((c = getc(ifp))!= EOF)
    if(count == 50){
     printf("\n");
     putc(c,ofp);
     count = 0;
     }
    else
    putc(c,ofp);

    count++;
}