c - "File Copying" section in K&R -


i'm new programming , can't seem head around why following happens in code, is:

#include <stdio.h>  /*copy input output; 1st version */  main() {     int c;  c = getchar(); while (c != eof) {     putchar(c);     c = getchar();     } } 

so after doing reading, i've gathered following:

  1. nothing executes until hit enter getchar() holding function.
  2. before hit enter, keystrokes stored in buffer
  3. when getchar() called upon, goes looks @ first value in buffer, becomes value, , removes value buffer.

my question when remove first c = getchar() resulting piece of code has same functionality original code, albeit before type smiley face symbol appears on screen. why happen? because putchar(c) doesn't hold code, , tries display c, isn't yet defined, hence outputs random symbol? i'm using code::blocks if helps.

the function listed echo every character type @ it. true i/o "buffered". keyboard input driver of operating system doing buffering. while it's buffering keys press, echoes each key @ you. when press newline driver passes buffered characters along program , getchar sees them.

as written, function should work fine:

c = getchar();   // (buffer) first char  while (c != eof) {  // while user has not typed ^d (eof)     putchar(c);     // put character retrieved     c = getchar();  // next character } 

because of keyboard driver buffering, echo every time press newline or exit ^d (eof).

the smiley face coming @yuhao described: might missing first getchar in ran, putchar echoing junk. 0, looks smiley on screen.


Comments

Popular posts from this blog

Ansible - ERROR! the field 'hosts' is required but was not set -

customize file_field button ruby on rails -

SoapUI on windows 10 - high DPI/4K scaling issue -