Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Printf on bytearray

Tags:

c

printf

I have the following struct:

/** The description of an ordinary 8+3 DOS directory entry. */
struct  dirent
{
    byte    d_name[8];  //!< space padded name
    byte    d_ext[3];   //!< space padded extension

    byte    d_attr;     //!< the file attributes

    ......
};

printf("%s\n", de.d_name);

The problem I'm facing is with the printing of d_name I get the following output: 'INSTALL BAT!' which is not the 8 chars I was expecting at most.

My guess is the printf function continues to search in memory for a string terminator character even though it exceeded the d_name boundary.

Is there a way to only get the 'INSTALL' printed or do I need to loop through the entire byte array and print the chars individually?

like image 784
user695505 Avatar asked Mar 17 '14 11:03

user695505


1 Answers

To print a char array that is space-padded (but not necessarily null-terminated) you can use a width specifier for printf:

printf("%.*s\n", sizeof de.d_name, de.d_name);
like image 92
Klas Lindbäck Avatar answered Sep 24 '22 03:09

Klas Lindbäck