0

I am using stat file system in a program and I want to print the device id using

printf("\nst_dev = %s\n",buf.st_dev);

but i am getting error:

warning: format ‘%s’ expects argument of type ‘char *’, but argument 2 has type ‘__dev_t’ [-Wformat=]

What should b used instead of %s here?

Ahmad Habib
  • 33
  • 1
  • 9
  • 1
    There's no format specifier for whatever `__dev_t` is ... maybe you should get [some documentation](http://pubs.opengroup.org/onlinepubs/009695399/basedefs/sys/stat.h.html) –  Apr 22 '18 at 07:37
  • Related: https://stackoverflow.com/questions/9635702/in-posix-how-is-type-dev-t-getting-used .. printing it is not an intended use for `dev_t`. Of course you **can** print it if you know the underlying data type, but then your program isn't portable any more. –  Apr 22 '18 at 07:41

2 Answers2

0

There isn't a specific format specifier for dev_t (aka __dev_t), but it should be an integer type of some kind. If you follow the rabbit hole of typedefs and defines in the standard header files you should eventually reach the base definition for the type. On my system the chain is:

typedef __dev_t dev_t;
__STD_TYPE __DEV_T_TYPE __dev_t;
#define __DEV_T_TYPE        __UQUAD_TYPE
#define __UQUAD_TYPE        __u_quad_t
__extension__ typedef unsigned long long int __u_quad_t;

Therefore %lu would work. It may be different on your system, but chances are it is something similar to unsigned long int. It's usually helpful to investigate these things when you encounter them, you never know what you might learn about how things work under the hood.

Roflcopter4
  • 679
  • 6
  • 16
  • The trouble is that what you "learn" only applies to your particular system; on some other system it may be different – M.M Apr 22 '18 at 08:21
  • Fair enough, perhaps it would have been more accurate to say that it is interesting to see how things work, rather than useful per se. In cases like this I think you could probably just get around the problem with a simple cast, but obviously it's not always so easy. – Roflcopter4 Apr 22 '18 at 10:57
0

st_dev is of type dev_t which is an integer type as per POSIX definition:

dev_t shall be an integer type.

So printing it using %s certainly wrong. There's no portable way to print it because there's no format specifier defined for it in POSIX. You could use intmax_t to print it:

printf("\nst_dev = %jd\n", (intmax_t)buf.st_dev);

If intmax_t isn't available (such as C89 systems) then you could cast it to long.

P.P
  • 117,907
  • 20
  • 175
  • 238