Keep Leading zeros C

2019-02-28 10:10发布

问题:

I am trying to read the memory addresses from /proc//maps and I use the following code

for (ptr = NULL; getline(&ptr, &n, file) > 0;)     {
   if (ptr[0]== ' ') { continue; }
   sscanf(ptr, "%lx-%lx", &r0, &r1);
   printf("r0: %lx, r1: %lx\n", r0, r1);           }

Assume that file points to /proc//maps & ptr is the line pointer. But when you consider a maps file, it doesn't read the file proper. It drops the zero, it does not pick the zeros up. So consider:

00110000-00123000 r-xp 00000000 08:01 129925     /lib/i686/cmov/libnsl-2.11.1.so

After running through my program:

r0: 110000, r1: 123000

How I keep the leading zeros to output something like this:

r0: 00110000, r1: 00123000

Edit: The printf is for debugging.

Here is what I do with r1 later on

mem = mmap(NULL, 4096, PROT_READ, MAP_PRIVATE, mem_fd, r1)

回答1:

You're reading these values into integers; integers don't have leading zeros.

If you know how many digits you want to pad out the length to, you can specify that in your format string:

printf("r0: %08lx, r1: %08lx\n", r0, r1);

There's no way to store and recall the exact number of leading zeroes without storing the value in a different format (e.g, a string), though.



回答2:

Use the 0 flag (which specifies leading zeros), followed by the padded length.

printf("r0: %08lx, r1: %08lx\n", r0, r1);
             ^^         ^^

This link is a good reference to look at.



标签: c getline scanf