[comp.lang.c] how to write a function that returns a string of N nulls

dipto@umbc3.UMD.EDU (Dipto Chakravarty ) (10/19/87)

I have a prog that takes two parameters. The first one is a port and
the second is an integer that specifies the length of the string to 
be sent to this port.

If N=4 then I have to send a "\0\0\0\0" to the port. How can I write
a function that will take N as a parameter and return a string _out
(which consists of N "\0"s to my main(). 

And secondly what form of fprintf or fwrite do I use to print out the
string from the main. The function itself can handle the output of the
string if passing it as parameter is messsy. 

Thanks in advance 
			Dipto Chakravarty     dipto@umbc3.umd.edu.ARPA

		

edw@IUS1.CS.CMU.EDU (Eddie Wyatt) (10/20/87)

In article <507@umbc3.UMD.EDU>, dipto@umbc3.UMD.EDU (Dipto Chakravarty ) writes:
> 
> I have a prog that takes two parameters. The first one is a port and
> the second is an integer that specifies the length of the string to 
> be sent to this port.
> 
> If N=4 then I have to send a "\0\0\0\0" to the port. How can I write
> a function that will take N as a parameter and return a string _out
> (which consists of N "\0"s to my main(). 


char *build_null_string(N)
    int N;
    {
    char *temp;
    extern char *malloc();

    temp = malloc(sizeof(char)*N);  /*  I actually never include
					the sizeof(char) */
    bzero(temp,sizeof(char)*N);
    return(temp);
    }

> 
> And secondly what form of fprintf or fwrite do I use to print out the
> string from the main. The function itself can handle the output of the
> string if passing it as parameter is messsy. 
> 


   What you probably want something like this :

	#define 	WRITEBLOCK	4

	write_null_chars(N,port)
 	    register int N;
	    FILE *port;
	    {
	    register int i, j;
	    static char a[WRITEBLOCK];
  			/* The static array should contain only zeros */

	    for (i = N; i >= WRITEBLOCK; i -= WRITEBLOCK)
		fwrite(a,sizeof(char),WRITEBLOCK,port);

	    for (j = i; j > 0; j--)
		fwrite(a,sizeof(char),1,port);
	    }
-- 

					Eddie Wyatt

e-mail: edw@ius1.cs.cmu.edu

rsalz@bbn.com (Rich Salz) (10/20/87)

If the ultimate goal is to write "N" ASCII NUL characters, then:
    #include <stdio.h>
    void
    putnul(n, f)
	register int n;
	register FILE *f;
    {
	while (--n >= 0)
	    (void)putc('\0', f);
    }

If the intermediate goal of getting a buffer of "N" zero-filled bytes
is also important, then look up calloc(3), bstring(3) and/or memory(3).
	/r$
-- 
For comp.sources.unix stuff, mail to sources@uunet.uu.net.