Hi ,

I have one buffer size is 50 bytes and reading 50 byte data from file

unsigned char bufffer[50];

read(fd,buffer,50); // Consider each byte numerical is value is zero.

printf("@@%s@@",buffer); // Here i will get @@@@ only.

But I want @@(50 zero)@@ as output(i have to use %c or %s only). If 25th byte numerical value is zero. It will print only 25 bytes only but i want print entire buffer if it has null terminal(ZERO) middle of the buffer also)

Any help !!

Dani AI

Generated

The core issue is that the buffer you read is raw/binary data, not a C string, so any string-format printing will stop at the first NUL byte. As pointed out, treat the data as binary; as showed, examining each byte is the common fix. Two quick safety notes before proceeding: always use the return value from read() to know how many bytes you actually received, and if you intend to use string APIs make room for a terminating NUL to avoid undefined behavior (read(2) man page, printf(3) man page).

Practical choices (pick based on desired visible output):

  • Send raw bytes unchanged to an output sink that accepts binary (use write/fwrite with the exact byte count). NULs will be transmitted but are invisible on a terminal.
  • If every zero byte must appear visibly (for example as the character '0' or an escape like "[00]"), create a separate printable buffer: allocate enough space, map each input byte to either its printable form or your chosen marker, terminate that buffer, then print it as a string. This lets you still call printf once while avoiding mid-buffer NULs.
  • For full safety and clarity, produce a hex/escaped dump (or use hexdump/xxd) so control characters cannot disturb the terminal.

Cautions: printing raw binary can trigger control characters (backspace, BEL, cursor moves). Use isprint()/classification or hex escapes when you need predictable, portable output.

Recommended Answers

All 3 Replies

One way to do it is to print each byte one at a time in a loop. %s is for null terminated strings. What you apparently have is a binary file, not a text file. There is no standard C function that will print that entire buffer the way you want it.

char buffer[BUFF_SIZE];

printf("string [");

for (i=0; i<BUFF_SIZE; i++)
{
    if (buffer[i] == '\0')
        printf("0");

    else
        printf("%c",buffer[i]);
}

printf("]\n");

there are more clever ways to do it but that gives you an idea

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.