Note that there are some explanatory texts on larger screens.

plurals
  1. POIs there a way to mmap a stdin?
    text
    copied!<p>I have a following problem:</p> <p>My job is to write a program that takes unsigned integer numbers that are passed to it through stdin and print out only the numbers that have more than 2 bits set to one. How should I do it efficiently? I did a version of a program where I read the numbers from a file using mmap, and it's quite quick. I read it like a very big *char buffer and using strtol I 'scrub' out each number and do my check and whatnot. </p> <p>Is there a way to operate on a string passed through stdin the same way? I though about buffering using fread, but there is a problem, where the buffer cuts off the number (meaning if i pass "1024 35" and I have a 6 byte buffer I will get "1024 3"), and I shudder to think how to get around that.</p> <p>Source:</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;sys/types.h&gt; #include &lt;sys/stat.h&gt; #include &lt;fcntl.h&gt; #include &lt;unistd.h&gt; #include &lt;sys/mman.h&gt; #include &lt;sys/types.h&gt; #include &lt;sys/stat.h&gt; #include &lt;sys/mman.h&gt; /* mmap() is defined in this header */ #include &lt;fcntl.h&gt; #include&lt;string.h&gt; #include"apue.h" int main (int argc, char *argv[]) { int fdin, fdout; char *src, *dst; struct stat statbuf; /* open the input file */ if ((fdin = open (argv[1], O_RDONLY)) &lt; 0) {printf("can't open %s for reading", argv[1]);return 1;} /* find size of input file */ if (fstat (fdin,&amp;statbuf) &lt; 0) {printf("fstat error");return 1;} /* mmap the input file */ if ((src = mmap (0, statbuf.st_size, PROT_READ, MAP_SHARED, fdin, 0)) == (caddr_t) -1) {printf("mmap error for input");return 1;} char* beg=src; long x; char* end=&amp;src[statbuf.st_size-1]; while(src&lt;end) { beg=src; x = strtol (src,&amp;src,10); if(!((x != 0) &amp;&amp; ((x &amp; (~x + 1)) == x))) fwrite(beg, 1, (int)(src-beg), stdout); } return 0; } </code></pre> <p><a href="http://pastebin.com/EVhG3x79" rel="nofollow">http://pastebin.com/EVhG3x79</a></p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload