0

As the title suggests I have to make a program to emulate the CAT commands, so far I have got basic input and output working however I need now include options such as -n.....

while((rd = getchar()) != EOF){
   if(putchar(rd) == EOF){
       perror("Write Err");
       return EXIT_FAILURE
   }

}

return EXIT_SUCCESS;

Whats the best way to go about printing options such as numbered lines or dollar signs to the actual output ?? Should I change my I/O methods to fgets and fputs (so I can then print out numbered lines, in a string format with the original input) Also should I use malloc realloc since there is no definite size of users input?

tshepang
  • 12,111
  • 21
  • 91
  • 136
  • I think using `sprintf()`, `fgets()` and `fputs()` might make your life easier. Dynamically allocating memory reduces memory usage but also comes with its own risks (memory leaks, fragmentation, etc.). I suggest you first get your program working properly and then convert it to use dynamic memory allocation. – Anish Ramaswamy Mar 05 '13 at 11:30
  • You can start from https://gist.github.com/pete/665971 to see various existing solutions – loreb Mar 05 '13 at 16:48

1 Answers1

0

In order to add line numbers and dollar signs, all you need to do is check whether the character being processed is a new line :

if (rd == '\n') {
        putchar($);
}

Dynamic memory allocation will not help here.

Using putchar() is inefficient. Switching to puts() would yield better performance. This would also require a more complicated logic.

Erwan Legrand
  • 4,148
  • 26
  • 26