Mail Archives: djgpp/1997/10/19/10:40:47
>>I once read a solution to this (can't remember where though!):
>>
>>The "fprintf" command will return the number of characters output,
>>and you should fopen DOS's "NULL" file to send the output to.
>>"NULL" is a "black hole" which will swallow and ignore anything you
>>send to it. Although "NULL" never appears in a directory, it
>>exists everywhere. (I think the UNIX equivalent is "/dev/nul",
>>but I've never used UNIX.)
This is a fine idea. It works with DJGPP (see below)
but I don't think that it is portable.
>Does anyone know if this works, and how compatible it is?
>Writing to a NULL pointer doesn't sound too good to me!
You don't write to a NULL pointer but to the NUL (one L) device.
Here is a test program that demonstrate the method
/************* cut here **************/
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
int get_sprintf_len(const char* format, ...)
{
va_list arg_ptr;
FILE* NulDevice;
int len;
va_start(arg_ptr, format);
NulDevice = fopen("NUL", "w");
len = vfprintf(NulDevice, format, arg_ptr);
fclose(NulDevice);
va_end(arg_ptr);
return len;
}
int main()
{
const char* message;
int len;
message = "Hello get_sprintf_len !\n";
len = get_sprintf_len("%s", message);
printf("len = %d\n", len);
if (len > 0)
{
char* str;
str = (char*) malloc(len + 1);
sprintf(str, "%s", message);
printf("Message copied is: %s\n", str);
free(str);
}
return 0;
}
Eyal
- Raw text -