Van
Van

Reputation: 49

C program read input file and output with "\n" new line every 50 characters

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

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

So, I have try:

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);
}

Am I supposed to use some type of pointers? Im not too good with C pointers, does anyone know? Thank you.

Upvotes: 0

Views: 1750

Answers (4)

Van
Van

Reputation: 49

Answer was :

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++;
}

Upvotes: 0

cosmos
cosmos

Reputation: 2303

Couple of issues:

  1. Your while loop needs braces
  2. '\n' not "\n"
  3. increment count

Your final code should look like this:

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++;
  }
}

Upvotes: 2

Eric J.
Eric J.

Reputation: 150148

Building on @Paul's correct answer, you can use modulo to decide when to output the newline:

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

Upvotes: 0

PaulProgrammer
PaulProgrammer

Reputation: 17680

your putc is attempting to output a string, which is actually a pointer. putc just takes the initial 8 bits as a char of the variable, which is most certainly not \n in this case.

You probably want (note the single quotes):

putc('\n', ofp);

If you are using windows, you may need to output \r\n to get the desired result.

Finally, your loop isn't testing for every 50 characters, it's outputting the value on each loop iteration. I assume you have done that as a test.

Upvotes: 2

Related Questions