我遇到了以下问题:
我的工作是编写一个程序,该程序通过stdin传递无符号整数并仅打印具有超过两个二进制位设置为1的数字。如何高效地完成这项任务?我编写了一个从文件中读取数字的版本,使用mmap非常快速。我像读取一个非常大的*char缓冲区一样读取它,并使用strtol“擦除”每个数字并进行检查等操作。
是否有一种方法可以通过stdin传递字符串并以相同的方式操作它?我考虑使用fread进行缓冲,但存在一个问题,即缓冲区截断了数字(这意味着如果我传递“1024 35”,并且我有一个6字节的缓冲区,我将得到“1024 3”),我不知道如何解决这个问题。
来源:
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/mman.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/mman.h> /* mmap() is defined in this header */
#include <fcntl.h>
#include<string.h>
#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)) < 0)
{printf("can't open %s for reading", argv[1]);return 1;}
/* find size of input file */
if (fstat (fdin,&statbuf) < 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=&src[statbuf.st_size-1];
while(src<end)
{
beg=src;
x = strtol (src,&src,10);
if(!((x != 0) && ((x & (~x + 1)) == x)))
fwrite(beg, 1, (int)(src-beg), stdout);
}
return 0;
}
unsigned int
形式fwrite到流中? - Medinoc1 2 3
并且任何在stdin中的东西正好在第二个数字之后结束,那么你如何知道2已经完成,并且不是实际上应该是1 23456 3
? - Marc Bmmap
所能获得的时间。保持简单。 - Kninnug