473,795 Members | 3,151 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Custom Scanf Routine

I have tried to write my custom scanf function on the lines of minprintf
provided in K&R2.In the function myscanf() i access memory directly
using the address passed to the function .Can it be dangerous ?

I am getting the correct output though.Any help is appreciated.

/*Include Files*/

/*Assisting Functions*/
int flushln(FILE *f){ /*Code*/}
char *input(char *message){/*Code*/}
static int getInt(void){/*Code*/}
/*My Custom Scanf Routine*/

int myscanf(const char* format,...)
{
va_list ap;
const char *p;
int count = 0;
int temp;

va_start(ap,for mat);
for( p = format ; *p ;p++) {
if( *p != '%'){
continue;
}
switch(*++p){
case 'd':
if(temp = getInt()){
*(long *)va_arg(ap,int ) = temp;/*Direct Memory Access*/
count ++;
}
else{ puts("Input Error"); }
break;
}
}
va_end(ap);
return count;
}

int main(void)
{
int a = 0,b = 0;
myscanf("%d %d",&a,&b);
printf("%d %d",a,b);

return 0;
}

Thanks!
Jul 3 '08
30 3465
Barry Schwarz wrote:
On Sun, 06 Jul 2008 14:26:12 +0530, Tarique <pe*****@yahoo. comwrote:
>Barry Schwarz wrote:
....snip..

Sorry but you fixed only half the problem.
The Best i've come so far :I've re-designed the error handling (looks
sane to me! ) and now process signed "Longs" and "Ints" separately !

/*
* File: main.c
* Author: Tarique
*
* Created on July 4, 2008, 11:07 PM
*/

#include <stdio.h >
#include <stdlib.h>
#include <string.h>
#include <limits.h>
#include <stdarg.h>
#include <errno.h >
/*
*
*/
struct ErrorCode {
int code ;
/*Pack any other info if required later on */
};

/*Provide Error Code to Differentiate between Errors*/
enum Ecodes {
E_OK = 0, /*Input Ok */
E_IO = 1, /*Input Stream Error */
E_EOF = 2, /*End of File Envountered */
E_TOOLONG = 3, /*Input Exceeds Buffer Length */
E_SHORTBUFF = 4, /*Destination Buffer is Short */
E_RANGE = 5, /*Number Exceeds Range */
E_BADINPUT = 6, /*Invalid Input Obtained */
E_DEFAULT = 7 /*All Unhandled Errors if Any */
};

/*
*If there is garbage in the input stream,pull off everything from the
*input stream to clear it for further use.
*/

int flushln(FILE *f) {
int ch;
while(('\n' != (ch = getc( f ))) && (EOF != ch))
;
return ch;
}

/*Takes a destination buffer and its size as arg (With Error Code) ;
*copies the user entered string into the destination buffer if input
* is successful and the caller's buffer is long enough to hold it.
*
*On Error ,clears the error and sets the appropriate error code which
*can be suitably utilized if necessary.
*/

void input( char* buff,
size_t buff_len,
struct ErrorCode* error ) {

#define BUFFSIZE 100 + 2

char buffer[ BUFFSIZE ];
char* p = buffer + BUFFSIZE - 1;
*p = !0;

if( fgets( buffer, BUFFSIZE, stdin ) == NULL ) {
if( ferror( stdin ) ) {
fprintf( stderr, "Input Stream Error \n" );
error->code = E_IO;
clearerr( stdin );
return ;
}
else if( feof( stdin ) ) {
fprintf( stderr, "EOF Encountered \n" );
error->code = E_EOF;
clearerr( stdin );
return ;
}
}

else {
if( !(*p || (*--p) == '\n') ) {
fprintf( stderr, "Too Long Input\n" );
error->code = E_TOOLONG;
flushln( stdin );
return ;
}
}

if( buff_len >= strlen(buffer) ) {
strcpy( buff, buffer );
error->code = E_OK;
return ;
}

else {
fprintf( stderr, "Too Long Input-b \n" );
error->code = E_SHORTBUFF;
return ;
}
}

/*
* If a string is successfully obtained from the input function,
*it is parsed using strtol. If no parsing error occurs, a long
*If there is any error zero is returned.
*/

long getLong(int isint,
struct ErrorCode* error ) {

char intbuff[21] = {0} ;
char* end_ptr = NULL;
long int lval = 0;
errno = 0;

printf("Enter :");
input( intbuff, 20, error );

if ( error->code == E_IO ) return 0;
else if( error->code == E_EOF ) return 0;
else if( error->code == E_TOOLONG ) return 0;
else if( error->code == E_SHORTBUFF ) return 0;

errno = 0;
lval = strtol( intbuff, &end_ptr, 10 );
if( ERANGE == errno ) {
fprintf(stderr, "Out of Range \n");
error->code = E_RANGE;
return 0;
}
else if (!((*end_ptr == '\n') || (*end_ptr == '\0') || (*end_ptr ==
' '))) {
error->code = E_BADINPUT;
fprintf( stderr, "Not a Valid Integer\n" );
return 0;
}
if(!isint) { /*Process long */
return lval;
}

else { /*Process Int*/
if ( lval INT_MAX ) {
error->code = E_RANGE;
fprintf( stderr, "Number too Large \n" );
return 0;
}
else if ( lval < INT_MIN ) {
error->code = E_RANGE;
fprintf( stderr, "Number too Small \n" );
return 0;
}
else
return lval;
}
}

/*Minimal Scanf routine only for signed
*'ints' and 'longs' as of now
*/

int myscanf( const char* format, ... ) {

va_list ap ;
const char* p;
int count = 0;
int temp = 0;
long int temp_long = 0;
struct ErrorCode iserror;
iserror.code = 0;

va_start( ap, format );

for( p = format ; *p ; p++ ) {
if( *p != '%' ) {
continue;
}
switch( *++p ) {
case 'd' :
temp = (int)getLong( 0, &iserror );
if( !iserror.code ) {
*va_arg( ap, int* ) = temp;
count ++ ;
}
else {
*va_arg( ap, int* ) = 0;
iserror.code = 0;
}

break;

case 'l':
if( (*++p) == 'd' ) {
temp_long = getLong( 1, &iserror );
if( !iserror.code ) {
*va_arg( ap, long * ) = temp_long;
count ++;
}
else {
*va_arg( ap, long * ) = 0;
iserror.code = 0;
}
}

break;

default :
break;
}
}
va_end(ap);
return count;
}
int main( void ) {

long a = 0, b = 0;
int c = 0, d = 0;

myscanf("%ld %ld" ,&a ,&b);
printf("%d %d \n",a,b);

myscanf("%d %d" ,&c ,&d);
printf("%d %d\n",c,d);

return (EXIT_SUCCESS);
}

Tarique.

Jul 7 '08 #21
I have just one small correction here...

In article <ln************ @nuthaus.mib.or g>
Keith Thompson <ks***@mib.orgw rote:
>I stumbled over your invocations of va_arg, such as:
> *va_arg( ap, int* ) = temp;
va_arg() is required to be a macro, and va_arg(ap, int*) expands to an
expression of type int*, so this seems to be valid.
It is.
>But note that an invocation of va_arg *looks like* a function call.
If it really were, then the unary "*" operator would apply to the name
"va_arg", not to the result of the call, and the assignment would be
invalid.
No, it is still valid even then:

*f() = var;

binds the same as:

(*(f())) = var;

because the function-call operator (the parentheses following an
identifier) binds more tightly than the unary-* dereference operator.

(As an aside, va_arg looks like a function call only superficially,
since its second argument is a type-name. Note also that the type
name is required to be one that can have one more unary "*" added
to the end, so va_arg is the only place in C where typedef is
actually required, though even then only sometimes. In particular,
to extract a parameter of type "pointer to function (args) returning
T", you cannot write:

va_arg(ap, T (args))

because the syntatic construct for "pointer to function returning T"
is not "T (args) *" but rather "T (*)(args)". But given:

typedef T alias(args);

we can then write:

va_arg(ap, alias)

This uses, or at least potentially uses, the syntactic construct
"alias *", which has type "pointer to function (args) returning
T", which is what we need.)
--
In-Real-Life: Chris Torek, Wind River Systems
Salt Lake City, UT, USA (40°39.22'N, 111°50.29'W) +1 801 277 2603
email: gmail (figure it out) http://web.torek.net/torek/index.html
Jul 10 '08 #22
Chris Torek <no****@torek.n etwrites:
I have just one small correction here...

In article <ln************ @nuthaus.mib.or g>
Keith Thompson <ks***@mib.orgw rote:
>>I stumbled over your invocations of va_arg, such as:
>> *va_arg( ap, int* ) = temp;
va_arg() is required to be a macro, and va_arg(ap, int*) expands to an
expression of type int*, so this seems to be valid.

It is.
>>But note that an invocation of va_arg *looks like* a function call.
If it really were, then the unary "*" operator would apply to the name
"va_arg", not to the result of the call, and the assignment would be
invalid.

No, it is still valid even then:

*f() = var;

binds the same as:

(*(f())) = var;

because the function-call operator (the parentheses following an
identifier) binds more tightly than the unary-* dereference operator.
[...]

You're right, as usual.

I'd still be happier with more parentheses, even though they're not
strictly necessary:

*(va_arg(ap, int*)) = temp;

--
Keith Thompson (The_Other_Keit h) ks***@mib.org <http://www.ghoti.net/~kst>
Nokia
"We must do something. This is something. Therefore, we must do this."
-- Antony Jay and Jonathan Lynn, "Yes Minister"
Jul 14 '08 #23
Chris Torek <no****@torek.n etwrites:
I have just one small correction here...

In article <ln************ @nuthaus.mib.or g>
Keith Thompson <ks***@mib.orgw rote:
>>I stumbled over your invocations of va_arg, such as:
>> *va_arg( ap, int* ) = temp;
va_arg() is required to be a macro, and va_arg(ap, int*) expands to an
expression of type int*, so this seems to be valid.

It is.
>>But note that an invocation of va_arg *looks like* a function call.
If it really were, then the unary "*" operator would apply to the name
"va_arg", not to the result of the call, and the assignment would be
invalid.

No, it is still valid even then:

*f() = var;

binds the same as:

(*(f())) = var;

because the function-call operator (the parentheses following an
identifier) binds more tightly than the unary-* dereference operator.
[...]

You're right, as usual.

I'd still be happier with more parentheses, even though they're not
strictly necessary:

*(va_arg(ap, int*)) = temp;

--
Keith Thompson (The_Other_Keit h) ks***@mib.org <http://www.ghoti.net/~kst>
Nokia
"We must do something. This is something. Therefore, we must do this."
-- Antony Jay and Jonathan Lynn, "Yes Minister"
Jul 14 '08 #24
Chris Torek <no****@torek.n etwrites:
I have just one small correction here...

In article <ln************ @nuthaus.mib.or g>
Keith Thompson <ks***@mib.orgw rote:
>>I stumbled over your invocations of va_arg, such as:
>> *va_arg( ap, int* ) = temp;
va_arg() is required to be a macro, and va_arg(ap, int*) expands to an
expression of type int*, so this seems to be valid.

It is.
>>But note that an invocation of va_arg *looks like* a function call.
If it really were, then the unary "*" operator would apply to the name
"va_arg", not to the result of the call, and the assignment would be
invalid.

No, it is still valid even then:

*f() = var;

binds the same as:

(*(f())) = var;

because the function-call operator (the parentheses following an
identifier) binds more tightly than the unary-* dereference operator.
[...]

You're right, as usual.

I'd still be happier with more parentheses, even though they're not
strictly necessary:

*(va_arg(ap, int*)) = temp;

--
Keith Thompson (The_Other_Keit h) ks***@mib.org <http://www.ghoti.net/~kst>
Nokia
"We must do something. This is something. Therefore, we must do this."
-- Antony Jay and Jonathan Lynn, "Yes Minister"
Jul 14 '08 #25
Chris Torek <no****@torek.n etwrites:
I have just one small correction here...

In article <ln************ @nuthaus.mib.or g>
Keith Thompson <ks***@mib.orgw rote:
>>I stumbled over your invocations of va_arg, such as:
>> *va_arg( ap, int* ) = temp;
va_arg() is required to be a macro, and va_arg(ap, int*) expands to an
expression of type int*, so this seems to be valid.

It is.
>>But note that an invocation of va_arg *looks like* a function call.
If it really were, then the unary "*" operator would apply to the name
"va_arg", not to the result of the call, and the assignment would be
invalid.

No, it is still valid even then:

*f() = var;

binds the same as:

(*(f())) = var;

because the function-call operator (the parentheses following an
identifier) binds more tightly than the unary-* dereference operator.
You're right, as usual.

I'd still be happier with more parentheses, even though they're not
strictly necessary:

*(va_arg(ap, int*)) = temp;

(Having trouble with my news server; I hope this shows up no more or
less than once.)

--
Keith Thompson (The_Other_Keit h) ks***@mib.org <http://www.ghoti.net/~kst>
Nokia
"We must do something. This is something. Therefore, we must do this."
-- Antony Jay and Jonathan Lynn, "Yes Minister"
Jul 14 '08 #26
Keith Thompson <ks***@mib.orgw rites:
[...]
(Having trouble with my news server; I hope this shows up no more or
less than once.)
Naturally it was posted 4 times. I might have to change news servers
again. I'll try posting this exactly once; if it fails, I won't
retry. We'll see what happens.

--
Keith Thompson (The_Other_Keit h) ks***@mib.org <http://www.ghoti.net/~kst>
Nokia
"We must do something. This is something. Therefore, we must do this."
-- Antony Jay and Jonathan Lynn, "Yes Minister"
Jul 14 '08 #27
On Jul 14, 9:20 pm, Keith Thompson <ks...@mib.orgw rote:
Keith Thompson <ks...@mib.orgw rites:

[...]
(Having trouble with my news server; I hope this shows up no more or
less than once.)

Naturally it was posted 4 times. I might have to change news servers
again. I'll try posting this exactly once; if it fails, I won't
retry. We'll see what happens.
You could try alt.test instead of posting here.
Your message appeared, I think you're just impatient with your slow?
news server :)
Jul 14 '08 #28
vi******@gmail. com writes:
On Jul 14, 9:20 pm, Keith Thompson <ks...@mib.orgw rote:
>Keith Thompson <ks...@mib.orgw rites:

[...]
(Having trouble with my news server; I hope this shows up no more or
less than once.)

Naturally it was posted 4 times. I might have to change news servers
again. I'll try posting this exactly once; if it fails, I won't
retry. We'll see what happens.
You could try alt.test instead of posting here.
Your message appeared, I think you're just impatient with your slow?
news server :)
Sorry again for the junk posts. None of them were intended to be test
posts, they just turned out that way. In at least one case, the
server apparently posted the article and then gave me an error
message. Most of the time it posts right away. I'll be more careful
in the future.

--
Keith Thompson (The_Other_Keit h) ks***@mib.org <http://www.ghoti.net/~kst>
Nokia
"We must do something. This is something. Therefore, we must do this."
-- Antony Jay and Jonathan Lynn, "Yes Minister"
Jul 14 '08 #29
Keith Thompson wrote:
vi******@gmail. com writes:
>On Jul 14, 9:20 pm, Keith Thompson <ks...@mib.orgw rote:
>>Keith Thompson <ks...@mib.orgw rites:

[...]

(Having trouble with my news server; I hope this shows up no more
or less than once.)

Naturally it was posted 4 times. I might have to change news
servers
again. I'll try posting this exactly once; if it fails, I won't
retry. We'll see what happens.
You could try alt.test instead of posting here.
Your message appeared, I think you're just impatient with your slow?
news server :)

Sorry again for the junk posts. None of them were intended to be test
posts, they just turned out that way. In at least one case, the
server apparently posted the article and then gave me an error
message. Most of the time it posts right away. I'll be more careful
in the future.
If your news server is motzarella.org then yes, this happens
occasionally to me too. If I receive an error message after I attempt
to post an article, I wait for five minutes, then check the group and
retry if the article has not appeared despite the error. Naturally it's
annoying but thankfully it doesn't happen often.

Jul 14 '08 #30

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

39
100815
by: Teh Charleh | last post by:
OK I have 2 similar programmes, why does the first one work and the second does not? Basically the problem is that the program seems to ignore the gets call if it comes after a scanf call. Please anything even a hint would be really helpful, I cant for the life of me see why the 2nd prog wont work... gets before scanf code:---------------------------------------------------------------------
14
2748
by: Peter Mount | last post by:
Hello I'm having trouble with " scanf("%c", &answer);" on line 20 below. When I run the program in cygwin on Windows 98SE it skips that line completely and ends the program. Does scanf have problems with "%c" or is it the operating system I'm using? 1 #include <stdio.h> 2 3 int main()
4
2280
by: Vig | last post by:
Is scanf or any other function capable of reading numbers in the format 1.2345d-13 where 'd' serves the same role as 'e' usually does in scientific notation? This operation is iterated through several times and we really would like not to have to read it as a string first or anything like that. Thanks -- Vig
6
3489
by: Rob Thorpe | last post by:
Given the code:- r = sscanf (s, "%lf", x); What is the correct output if the string s is simply "-" ? If "-" is considered the beginning of a number, that has been cut-short then the correct output is that r = EOF. If it is taken to be a letter in the stream, then the output should be r = 0, as far as I can see. My compiler gives EOF.
3
14146
by: linguae | last post by:
Hello. In my C program, I have an array of character pointers. I'm trying to input character strings to each index of the character pointer array using scanf(), but when I run the program, I get segmentation faults and core dumps. The problem occurs when the program calls scanf(). I don't know what is wrong with it. Here is my code: #include "stdio.h" #define SIZE 5
185
17482
by: Martin Jørgensen | last post by:
Hi, Consider: ------------ char stringinput ..bla. bla. bla. do {
62
5065
by: Argento | last post by:
I was curious at the start about how ungetc() returns the character to the stream, so i did the following coding. Things work as expected except if I change the scanf("%c",&j) to scanf("%d",&j). I don't understand how could scanf() affect the content of i and i. Can someone tell me why? #include <stdio.h> #include <ctype.h> void main() {
4
6453
by: Val | last post by:
I have a complex object that I need to serialize. Rather than rely on a standard routine, which is called during the serialization/deserialization, I would like to be able to use my own functions that would convert this object into a string and would then write that string to a file. Upon deserialization, I need to be able to call another custom function to recreate the object. I have looked and both implementing the ISerializable...
26
9544
by: vid512 | last post by:
hi. i wanted to know why doesn't the scanf functions check for overflow when reading number. For example scanf("%d" on 32bit machine considers "1" and "4294967297" to be the same. I tracked to code to where the conversion itself happens. Code in scanfs just ignores return value from conversion procedures. More info in case of glibc posted here:
0
9672
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10214
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10164
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10001
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9042
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6780
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5563
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3727
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2920
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.