-1

Here is my code but it is not making any output to console window. I need to print from output file and also wrap the lines for a particular number of characters, say, 20 character per line:

#include <stdio.h>
#define SIZE 100

int
main (int argc, char *argv[])
{
  FILE *fp = NULL;
  char line[SIZE] = { 0 };
  int i = 0;

  for (i = 0; i < argc; i++)
    {
      printf ("The argc %d is %s\n", i, argv[i]);
    }

  fp = fopen (argv[1], "r");
  if (fp == NULL)
    {
      printf ("Can't open input file\n");
    }
  else
    {
      while (!feof (fp))
        {
          if (fgets (line, sizeof line, fp))
            {
              printf ("%s", line);
            }
        }
    }

  if (fclose (fp) != 0)
    {
      printf ("Error closing file\n");
    }

  return 0;
}
abligh
  • 24,573
  • 4
  • 47
  • 84
zam
  • 181
  • 2
  • 6
  • 18
  • 1
    Unrelated to your problem, but you should really read [Why is “while ( !feof (file) )” always wrong?](http://stackoverflow.com/questions/5431941/why-is-while-feof-file-always-wrong). – Some programmer dude Dec 06 '15 at 16:05
  • Is this `ifp = ...` a typo? `ifp ` is not defined. – alk Dec 06 '15 at 16:07
  • 1
    "*... it is not making any output ...*" really *nothing*? – alk Dec 06 '15 at 16:09
  • 1
    Your code does nothing to perform line wrapping. Are you asking about line-wrapping or asking about lack of output? If you want to wrap long lines, it will be easier to read/write one character at a time. Every 20 characters, insert a newline, reset the counter whenever a newline is output (whether inserted or from the file). You also then won't need the `line` buffer. – Clifford Dec 06 '15 at 16:32

1 Answers1

0

Your code makes no attempt to do line wrapping.

What you need to do (broadly speaking) is as follows:

  1. Maintain a temporary buffer
  2. Read each line of the file
  3. If the line read is \n (only), output the buffer followed by \n, and go to 2.
  4. If the buffer is empty, THEN replace the buffer by the line that is read ELSE append a space to the buffer and append the line read to the buffer.
  5. If the buffer has more than 20 characters (if you are line wrapping on twenty characters), find the 20th character, and count backwards until you find a white space. Output the buffer up to that character with a \n, and replace the buffer by the data in the buffer after the whitespace.
  6. At the end, output any remaining characters in the buffer followed by \n.

Implementing this is left as an exercise for the reader (we can't do all your homework for you).

Please also see @JoachimPileborg's wise advice re reading 'Why is while ( !feof (file) ) always wrong?'

Community
  • 1
  • 1
abligh
  • 24,573
  • 4
  • 47
  • 84