• C

Weird chars when printing

Hi folks,

I got troubles when using printf. I got some weird chars.

I have a struct

struct permission {
      char dl;
      char owner_read;
      char owner_write;
      char owner_exe;
      char grp_read;
      char grp_write;
      char grp_exe;
      char other_read;
      char other_write;
      char other_exe;
   };

   struct permission modes;

Then

   modes.dl=            (S_ISDIR(filebuff.st_mode))      ? 'd' :'-';
   modes.owner_read=      (filebuff.st_mode & S_IRUSR)==S_IRUSR ? 'r':'-';
   modes.owner_write=      (filebuff.st_mode & S_IWUSR)==S_IWUSR ? 'w':'-';
   modes.owner_exe=      (filebuff.st_mode & S_IXUSR)==S_IXUSR ? 'x':'-';
   modes.grp_read=      (filebuff.st_mode & S_IRGRP)==S_IXGRP ? 'r':'-';
   modes.grp_write=      (filebuff.st_mode & S_IWGRP)==S_IXGRP ? 'w':'-';
   modes.grp_exe=      (filebuff.st_mode & S_IXGRP)==S_IXGRP ? 'x':'-';
   modes.other_read=      (filebuff.st_mode & S_IROTH)==S_IROTH ? 'r':'-';
   modes.other_write=      (filebuff.st_mode & S_IWOTH)==S_IWOTH ? 'x':'-';
   modes.other_exe=       (filebuff.st_mode & S_IXOTH)==S_IXOTH ? 'x':'-';

Finally

   printf("%5u %10s %d %3u %8ld %s\n",
        filebuff.st_ino,
        modes,
        filebuff.st_uid,
        filebuff.st_nlink,
        filebuff.st_size,
        entry->d_name);

(ps: struct dirent *entry)

But I got something like:

9830207 -rw-------Š@ 37796   1      100 Makefile

There is a weird char after the (file's) mode

Why?

Thanks

LVL 1
tiger0516Asked:
Who is Participating?
 
ozoCommented:
There is no guarantee that a struct can be printed with %s
It looks like you got lucky and your c implementaion happened to allign the characters in a way that worked for the first 10 characters,
but you still have to limit the print to only 10 characters with
%.10s
0
 
Kent OlsenData Warehouse Architect / DBACommented:
Hi tiger0516,

There's probably some junk in memory right after the string that you formatted.

Either make it one byte longer and insert a zero into it or change the print format to print exactly 9 characters.

   printf("%5u %10s %d %3u %8ld %9.9s\n",
       filebuff.st_ino,
       modes,
       filebuff.st_uid,
       filebuff.st_nlink,
       filebuff.st_size,
       entry->d_name);


Good Luck!
Kent
0
 
Kent OlsenData Warehouse Architect / DBACommented:
Hi ozo,

Seems a little odd the the default behavior is #pragma pack, huh?


Kent
0
 
ozoCommented:
#pragma is implementation defined.
there is no guarantee that it will work in a differerent implementation
But since it seems to be packed in this implementation,
printf("%5u %.10s %d %3u %8ld %s\n"
should work unportably to deal with the symptom described
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.