473,785 Members | 2,737 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 #1
30 3462
Hi

On Fri, 04 Jul 2008 03:12:09 +0530, Tarique wrote:
I have tried to write my custom scanf function
*(long *)va_arg(ap,int ) = temp;
That is a very bad idea, it might work on certain systems where pointers
are the same size as integers, but that is often not the case.

Even if this does work once, the next operation on ap might fail.

va_arg needs to be told the type of the argument that was written in
place of the ... in when the function was called. You should always put
the correct type in the second argument. In most cases that means you
won't need to cast the return.

* va_arg(ap,long* ) = temp;

will work perfectly, as long as a long pointer was really written at the
current place in the argument list.

HTH
viza
Jul 4 '08 #2
Tarique wrote:
....snip...

This is my code for a minimal custom scanf function(for entering valid
ints n longs with error checking)
I would be really grateful if someone can review it.Comments awaited!

Thank You

#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <limits.h>
#include <stdarg.h>

#define BUFFSIZE 98 + 2 /*Used by input()*/

/*Clear The Input stream if required*/
int flushln(FILE *f) {
int ch;
while (('\n' != (ch = getc( f ))) && (EOF != ch))
continue;
return ch;
}

/*Accept a string from user (parse later on)*/
char *input(const char* message,char *buff)
{
char buffer[ BUFFSIZE ];
char *p = &buffer[ BUFFSIZE-1 ];

if(message != "")
puts(message);

buffer[BUFFSIZE -1] = '$';

if( fgets(buffer,BU FFSIZE,stdin) == NULL) {
if(ferror(stdin )) {
perror("Input Stream Error");
clearerr( stdin );
return "I/O";
}
if(feof(stdin)) {
perror("EOF Encountered");
clearerr( stdin );
return "EOF";
}
}
else{
if(!((*p == '$') || ( (*p == '\0') && (*--p == '\n') ))) {
flushln(stdin);
puts("Too long input!\n\n");
return NULL;
}
}
strcpy(buff,buf fer);
return buff;
}

/*Accept a string and pass a valid long int if possible,else return 0*/
long getInt(void)
{
char intbuff[100];
char *buffptr = intbuff;
char *end_ptr;
long int lVal;
int trial = 1; /*No of tries on wrong input*/
int dist=0;
errno = 0;

while(trial-- != 0)
{
buffptr = input("Enter :",intbuff);
if (buffptr == "I/O" || buffptr == "EOF" || buffptr == NULL)
return 0;

lVal= strtol(buffptr, &end_ptr, 0);
if (ERANGE == errno){
perror("Out of Range");
}
else if (lVal INT_MAX){
perror("Too Large!");
}
else if (lVal < INT_MIN){
perror("Too Small");
}
else if (end_ptr == buffptr){
printf("Not a Valid Integer\n\n");
}
else
return lVal;
}
return 0;
}

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 =(int)getInt()) {
*va_arg(ap,long *) = temp;/* Direct Memory Access to MEM */
count ++;
}
else break;
break;

case 'l':
if((*++p) == 'd'){
if(temp =getInt()){
*va_arg(ap,long *) = temp;/* Direct Memory Access to MEM */
count ++;
p--;
}
else {
*va_arg(ap,long *) = 0;/*Invalid input ,so set variable to zero*/
p--;
break;
}
}
break;
default:
break;
}
}
va_end(ap);
return count;
}

int main(void)
{
long int a = 0,b = 0;
int c = 0,d = 0;

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

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

return 0;
}
Jul 4 '08 #3
Tarique wrote:
Tarique wrote:
...snip...

This is my code for a minimal custom scanf function(for entering valid
ints n longs with error checking)
I would be really grateful if someone can review it.Comments awaited!

Thank You
Just a note. Haven't seen it in detail, sorry.

Also in future please use spaces in place of tabs when posting to
Usenet. As you can see below, some software on the Usenet stripped out
all your tabs, rendering unformatted code, which is very difficult to
read.
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <limits.h>
#include <stdarg.h>

#define BUFFSIZE 98 + 2 /*Used by input()*/

/*Clear The Input stream if required*/
int flushln(FILE *f) {
int ch;
while (('\n' != (ch = getc( f ))) && (EOF != ch))
continue;
return ch;
}

/*Accept a string from user (parse later on)*/
char *input(const char* message,char *buff)
{
char buffer[ BUFFSIZE ];
char *p = &buffer[ BUFFSIZE-1 ];

if(message != "")
puts(message);

buffer[BUFFSIZE -1] = '$';

if( fgets(buffer,BU FFSIZE,stdin) == NULL) {
if(ferror(stdin )) {
perror("Input Stream Error");
clearerr( stdin );
return "I/O";
}
if(feof(stdin)) {
perror("EOF Encountered");
clearerr( stdin );
return "EOF";
}
}
else{
if(!((*p == '$') || ( (*p == '\0') && (*--p == '\n') ))) {
flushln(stdin);
puts("Too long input!\n\n");
return NULL;
}
}
strcpy(buff,buf fer);
return buff;
}

/*Accept a string and pass a valid long int if possible,else return
0*/ long getInt(void)
{
char intbuff[100];
char *buffptr = intbuff;
char *end_ptr;
long int lVal;
int trial = 1; /*No of tries on wrong input*/
int dist=0;
errno = 0;

while(trial-- != 0)
{
buffptr = input("Enter :",intbuff);
if (buffptr == "I/O" || buffptr == "EOF" || buffptr == NULL)
return 0;

lVal= strtol(buffptr, &end_ptr, 0);
if (ERANGE == errno){
perror("Out of Range");
}
else if (lVal INT_MAX){
perror("Too Large!");
}
else if (lVal < INT_MIN){
perror("Too Small");
}
What will you do on implementations where INT_MAX == LONG_MAX and
INT_MIN == LONG_MIN?

<snip rest>

Jul 4 '08 #4
On Fri, 04 Jul 2008 18:10:51 +0530, Tarique wrote:
I would be really grateful if someone can review it.Comments awaited!
#define BUFFSIZE 98 + 2 /*Used by input()*/
Generally it's not smart to use arbitrary fixed length buffers. Are you
certain that the input won't be bigger? If your code is well written
then it that would cause it to fail, and if it is not well written then
it could FEYC (f***ing explode your computer).
/*Clear The Input stream if required*/ int flushln(FILE *f) {
int ch;
while (('\n' != (ch = getc( f ))) && (EOF != ch))
continue;
return ch;
}
Gah! ugly. It's best that you don't use assignments as truth values,
especially as a beginner. That continue is superfluous too. I would
also ungetc() the character and return void.
/*Accept a string from user (parse later on)*/ char *input(const char*
message,char *buff) {
char buffer[ BUFFSIZE ];
char *p = &buffer[ BUFFSIZE-1 ];
char *p= buffer + BUFSIZE - 1; might be easier to read.
if(message != "")
You can't do that in C. Well, you can, but it doesn't mean what you
think. Lookup the strcmp() function.
puts(message);
buffer[BUFFSIZE -1] = '$';
if( fgets(buffer,BU FFSIZE,stdin) == NULL) {
if(ferror(stdin )) {
perror("Input Stream Error");
clearerr( stdin );
return "I/O";
It's not usual to return strings like that one. In case of error perhaps
you might want to return NULL.
}
if(feof(stdin)) {
perror("EOF Encountered");
clearerr( stdin );
return "EOF";
}
}
else{
if(!((*p == '$') || ( (*p == '\0') && (*--p == '\n') )))
{
flushln(stdin);
puts("Too long input!\n\n");
return NULL;
}
}
strcpy(buff,buf fer);
If you know that buff is at least as big as buffer, why do you need
buffer in the first place? Read to buff.
return buff;
}

/*Accept a string and pass a valid long int if possible,else return 0*/
long getInt(void)
{
char intbuff[100];
char *buffptr = intbuff;
char *end_ptr;
long int lVal;
int trial = 1; /*No of tries on wrong input*/ int dist=0;
errno = 0;

while(trial-- != 0)
{
buffptr = input("Enter :",intbuff);
if (buffptr == "I/O" || buffptr == "EOF" || buffptr == NULL)
return 0;

lVal= strtol(buffptr, &end_ptr, 0);
if (ERANGE == errno){
You didn't set errno to zero. Well you did, but it might have changed
many times since then. Do it immediately before each conversion.

I haven't gome through it all, but HTH
viza
Jul 4 '08 #5
viza wrote:
...snip...
>
I haven't gome through it all, but HTH
viza
@Santosh and Viza

Thanks for the quick review.Ive pasted the code here :
http://phpfi.com/329176
Hope it is easier to read.
Jul 4 '08 #6
On Fri, 04 Jul 2008 18:10:51 +0530, Tarique <pe*****@yahoo. comwrote:
>This is my code for a minimal custom scanf function(for entering valid
ints n longs with error checking)
I would be really grateful if someone can review it.Comments awaited!

Thank You

#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <limits.h>
#include <stdarg.h>

#define BUFFSIZE 98 + 2 /*Used by input()*/

/*Clear The Input stream if required*/
int flushln(FILE *f) {
int ch;
while (('\n' != (ch = getc( f ))) && (EOF != ch))
continue;
return ch;
}

/*Accept a string from user (parse later on)*/
char *input(const char* message,char *buff)
{
char buffer[ BUFFSIZE ];
char *p = &buffer[ BUFFSIZE-1 ];

if(message != "")
puts(message);

buffer[BUFFSIZE -1] = '$';

if( fgets(buffer,BU FFSIZE,stdin) == NULL) {
if(ferror(stdin )) {
perror("Input Stream Error");
clearerr( stdin );
return "I/O";
}
if(feof(stdin)) {
perror("EOF Encountered");
clearerr( stdin );
return "EOF";
}
}
else{
if(!((*p == '$') || ( (*p == '\0') && (*--p == '\n') ))) {
Please don't use tabs, especially within a line.

This test is backwards. If *p is '$', then a short line was entered
and there is nothing to flush. If the second half is true, exactly
BUFFSIZE-1 characters were entered (including the Enter key) and there
is still nothing to flush.

An easier test would be to set buffer[BUFFSIZE-2] to '\n'. If it is a
different non-zero value after the fgets, then too much data was
entered.
> flushln(stdin);
puts("Too long input!\n\n");
return NULL;
}
}
strcpy(buff,buf fer);
return buff;
}

/*Accept a string and pass a valid long int if possible,else return 0*/
long getInt(void)
{
char intbuff[100];
char *buffptr = intbuff;
char *end_ptr;
long int lVal;
int trial = 1; /*No of tries on wrong input*/
int dist=0;
errno = 0;

while(trial-- != 0)
{
buffptr = input("Enter :",intbuff);
if (buffptr == "I/O" || buffptr == "EOF" || buffptr == NULL)
return 0;

lVal= strtol(buffptr, &end_ptr, 0);
You need to indent consistently. This statement is not part of the
range of the preceding if. It should be indented to the same level as
that if.
> if (ERANGE == errno){
You should reset errno before calling strtol so that you don't process
residual data. strtol is not allowed to reset errno so you must do
it.
> perror("Out of Range");
}
else if (lVal INT_MAX){
perror("Too Large!");
}
else if (lVal < INT_MIN){
perror("Too Small");
}
else if (end_ptr == buffptr){
printf("Not a Valid Integer\n\n");
This is insufficient. Input of the form "123abc" will appear valid.
To be sure that strtol processed all the characters, make sure end_ptr
points to either '\n' or '\0'.
> }
else
return lVal;
How do you distinguish between input of 0 and one of the "error"
conditions such as "I/O"?
> }
return 0;
}

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){
These two statements are within the range of the for but you indenting
makes them look independent.
> case 'd':
if(temp =(int)getInt()) {
The cast is not needed.

Why are you using %d to describe a long and confuse everyone.

Why do you not accept 0 as valid input?
> *va_arg(ap,long *) = temp;/* Direct Memory Access to MEM */
count ++;
}
else break;
This is superfluous. If you remove it, the code will behave the same.
> break;

case 'l':
if((*++p) == 'd'){
if(temp =getInt()){
*va_arg(ap,long *) = temp;/* Direct Memory Access to MEM */
count ++;
p--;
}
else {
*va_arg(ap,long *) = 0;/*Invalid input ,so set variable to zero*/
I still don't understand why 0 is illegal but it sure seems like a
deliberate decision.
> p--;
break;
}
}
break;
default:
break;
}
If the value processed for %d is 0, you do not store any value for the
corresponding argument AND you do not pop the argument off the list.

If the value processed for %ld is 0, you store 0 and pop the argument
but don't increment count.

There could be an inconsistency between the value of count returned
and which arguments contain valid data.
> }
va_end(ap);
return count;
}

int main(void)
{
long int a = 0,b = 0;
int c = 0,d = 0;

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

myscanf("%d %d",&c,&d);
Here you invoke undefined behavior. myscanf will treat &c and &d as
long int* when they aren't. I think you meant for myscanf to extract
an int*, not a long*, for the %d case.
> printf("%d %d",c,d);

return 0;
}

Remove del for email
Jul 4 '08 #7
On Fri, 04 Jul 2008 14:30:08 -0700, Barry Schwarz <sc******@dqel. com>
wrote:
>On Fri, 04 Jul 2008 18:10:51 +0530, Tarique <pe*****@yahoo. comwrote:
>>This is my code for a minimal custom scanf function(for entering valid
ints n longs with error checking)
I would be really grateful if someone can review it.Comments awaited!

Thank You

#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <limits.h>
#include <stdarg.h>

#define BUFFSIZE 98 + 2 /*Used by input()*/

/*Clear The Input stream if required*/
int flushln(FILE *f) {
int ch;
while (('\n' != (ch = getc( f ))) && (EOF != ch))
continue;
return ch;
}

/*Accept a string from user (parse later on)*/
char *input(const char* message,char *buff)
{
char buffer[ BUFFSIZE ];
char *p = &buffer[ BUFFSIZE-1 ];

if(message != "")
puts(message);

buffer[BUFFSIZE -1] = '$';

if( fgets(buffer,BU FFSIZE,stdin) == NULL) {
if(ferror(stdin )) {
perror("Input Stream Error");
clearerr( stdin );
return "I/O";
}
if(feof(stdin)) {
perror("EOF Encountered");
clearerr( stdin );
return "EOF";
}
}
else{
if(!((*p == '$') || ( (*p == '\0') && (*--p == '\n') ))) {

Please don't use tabs, especially within a line.

This test is backwards.
Obviously I missed the !.
Remove del for email
Jul 5 '08 #8
viza wrote:
Tarique wrote:
.... snip ...
>
>/*Clear The Input stream if required*/ int flushln(FILE *f) {
int ch;
while (('\n' != (ch = getc( f ))) && (EOF != ch))
continue;
return ch;
}

Gah! ugly. It's best that you don't use assignments as truth
values, especially as a beginner. That continue is superfluous
too. I would also ungetc() the character and return void.
Not in the least ugly. Apart from the awkward location of the
initial comment. Works like a charm, too. The continue prevents
misreading an isolated semi. Your ungetc recommendation would make
the routine fail to perform the function indicated by the name.

--
[mail]: Chuck F (cbfalconer at maineline dot net)
[page]: <http://cbfalconer.home .att.net>
Try the download section.
Jul 5 '08 #9
On Fri, 04 Jul 2008 19:48:08 -0400, CBFalconer wrote:
viza wrote:
>Tarique wrote:
>>/*Clear The Input stream if required*/ int flushln(FILE *f) {
int ch;
while (('\n' != (ch = getc( f ))) && (EOF != ch))
continue;
return ch;
}

Gah! ugly. It's best that you don't use assignments as truth values,
especially as a beginner. That continue is superfluous too. I would
also ungetc() the character and return void.

Not in the least ugly.
I wouldn't take it home.
Apart from the awkward location of the initial comment. Works like a
charm, too. The continue prevents misreading an isolated semi.
Your ungetc recommendation would make the routine fail to perform the
function indicated by the name.
True. I misread the ugly loop construct and thought it read one-past the
newline.
Jul 5 '08 #10

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

Similar topics

39
100813
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
2747
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
14144
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
17478
by: Martin Jørgensen | last post by:
Hi, Consider: ------------ char stringinput ..bla. bla. bla. do {
62
5059
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
6452
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
9534
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
9480
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10324
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10147
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
10090
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
9949
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
8971
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
6739
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
5380
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5511
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?

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.