954,535 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Own getchar function

If you would have to write your own implementation of the
function getchar() in C; how would you do it?.

Aia
Nearly a Posting Maven
2,392 posts since Dec 2006
Reputation Points: 2,224
Solved Threads: 218
 

If creating that function for a standard compiler, you need to adhere to the C/C++ specification. The implementation is upto you. If you want to have a look at some of the implementations see this and this.

~s.o.s~
Failure as a human
Administrator
11,938 posts since Jun 2006
Reputation Points: 3,281
Solved Threads: 734
 
If you would have to write your own implementation of the function getchar() in C; how would you do it?.


I wouldn't. It a C primitive function and is written to access the keyboard input buffer, which is generally beyond the compiler's capability.

WaltP
Posting Sage w/ dash of thyme
Moderator
10,506 posts since May 2006
Reputation Points: 3,348
Solved Threads: 944
 
If you would have to write your own implementation of the function getchar() in C; how would you do it?.

It would have to be compiler and os specific which is why the C standards did not dictate how the function is to be implemented. You could use non-standard functions in conio.h like kbhit() and getch(), assuming your compiler supports those functions. For 32-bit programs that run under MS-Windows you could use the win32 api console functions. Don't know about MAC or *nix.

Ancient Dragon
Retired & Loving It
Team Colleague
30,050 posts since Aug 2005
Reputation Points: 5,662
Solved Threads: 2,343
 

getc_unlocked() and getchar_unlocked() functions conform to IEEE Std 1003.1-2001
(POSIX.1). so every *nix (mac is *nix below the hood) should have them as part of the
base system. (in linux, it would be in glibc.)

"getc_unlocked() and getchar_unlocked()functions are equivalent to getc() & getchar()
respectively, except that the caller is responsible for locking the stream with
flockfile(3) before calling them. These functions may be used to avoid the
overhead of locking the stream for each character, and to avoid input being
dispersed among multiple threads reading from the same stream."
-- from freebsd man pages.
i guess most *nix implementations would implement getchar as
flockfile, getchar_unlocked, unflockfile

vijayan121
Posting Virtuoso
1,606 posts since Dec 2006
Reputation Points: 1,159
Solved Threads: 287
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You