printf bad ?

Peter plp-ysDPMY98cNQDDBjDh4tngg at public.gmane.org
Sat Mar 19 11:18:07 UTC 2005


Here is a test program and its makefile for an octal-less strtoul that 
uses base=1 as flag for this type of conversion;

Subject: Files: 'new_strtoul' (Sat Mar 19 13:15:14 IST 2005)

--- begin '2.c' ---
/*
  * 2.c test program for 'octal bug' in strtoul() and simple fix
  *
  * plp 2005
  */
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <errno.h>

// new strtoul adds option base=1 for default decimal conversion - plp
unsigned long int new_strtoul(const char *a, char **z, int base);

int main(int argc, char *argv[])
{
 	char *p, *q;
 	double v;
 	int i;
 	unsigned long int l;

 	if(argc != 2) {
 		printf("usage: ./2 <number>\n");
 		exit(1);
 	}

 	i = atoi(argv[1]);
 	printf("atoi: %d\n",i);

 	p = q = argv[1];
 	errno = 0;
 	v = strtod(p,&q);
 	if(q==p)
 		printf("strtod: failed\n");
 	else
 		printf("strtod: %f\n",v);
 	if(errno)
 		perror("errno: ");

 	p = q = argv[1];
 	errno = 0;
 	l = strtoul(p,&q,0);
 	if((q==p)||*q)
 		perror("strtoul: failed: ");
 	else
 		printf("strtoul: %lu\n",l);
 	if(errno)
 		perror("errno: ");

 	p = q = argv[1];
 	errno = 0;
 	l = new_strtoul(p,&q,1);
 	if((q==p)||*q)
 		perror("new_strtoul: failed: ");
 	else
 		printf("new_strtoul: %ld (0x%lX)\n", l, l );
 	if(errno)
 		perror("errno: ");

 	exit(0);
}

// use base=1 to convert numbers using decimal default base,
// even if leading 0s are present. Also accept binary using
// prefix 0b. - plp
unsigned long int new_strtoul(const char *a, char **z, int b)
{
 	if(b==1) {
 		while( *a && *(a+1) && (*a=='0') && isdigit(*(a+1)) )
 			++a;
 		if( *a && *(a+1) && *(a+2) && (*a=='0') &&
 			isdigit(*(a+2)) && ((*(a+1)=='b') || (*(a+1)=='B')) )
 				return(strtoul(a+2,z,2));
 		b=0;
 		// this may break some program assumptions
 		// about z if the conversion fails
 		if(z)
 			*z = (char*) a;
 	}
 	return(strtoul(a,z,b));
}
--- end '2.c' ---
--- begin 'makefile' ---
#
# makefile for 2.c my_strtoul test
#
# plp 2005
#
# build: make
# run: ./2 012 (for example)
#
CC 	= gcc
CFLAGS 	= -Wall -g
SRCS 	= 2.c makefile

ALL: 2

clean:
 	rm -f 2

mailto:
 	D=`pwd`; B=`basename $$D`; \
 	echo -n "email '$$B' files to: "; read ADDR; \
 	for f in $(SRCS); do echo "--- begin '$$f' ---"; cat $$f;\
 	echo "--- end '$$f' ---"; done |\
 		mail -s "Files: '$$B' ($$(date))" "$$ADDR"


--- end 'makefile' ---
--
The Toronto Linux Users Group.      Meetings: http://tlug.ss.org
TLUG requests: Linux topics, No HTML, wrap text below 80 columns
How to UNSUBSCRIBE: http://tlug.ss.org/subscribe.shtml





More information about the Legacy mailing list