如何将stdin扫描成可变数量的流

时间:2013-02-17 18:54:30

标签: c scanf

我想将stdin扫描到可变数量的char数组中。像这样:

char words1[num][100];    //num passed as command line argument
i = 0;
for (i = 0; i < num; ++i)
{
    While (fscanf(stdin, "%s %s %s ...", words[i], words[i + 1], word[i + 2] ...) != EOF)
    {
         fprintf(outFileStream, "%s", words[i];
    }
}

目标是将stdin拆分为num个文件流,以便多个进程处理文件排序。我想也许vfscanf会有所帮助,但你仍然需要知道要发送多少格式说明符。我想我可以循环播放strcat(format, " %s")并将vfscanfva_list一起使用?有人能举个例子吗?

1 个答案:

答案 0 :(得分:1)

如果我正确理解您的问题,我认为您不需要复杂的fscanf格式,但一次只能读取一个字符串。也就是说,你可以使用类似的东西:

#include <stdio.h>

int main (int argc, char** argv) {
    int num = atoi(argv[1]);
    char words[num][100];
    int i = 0;
    while (fscanf(stdin,"%s",words[i]) > 0) { 
       fprintf(stdout,"Stream %d: %s\n",i,words[i]);
       i = (i + 1 ) % num;
    }
}

给定输入文件texta.txt如下:

a
b
c
d
e
f
g
h
i
j
k
l
m
n

...然后上面的程序会给出:

$ ./nstream 4 <texta.txt
Stream 0: a
Stream 1: b
Stream 2: c
Stream 3: d
Stream 0: e
Stream 1: f
Stream 2: g
Stream 3: h
Stream 0: i
Stream 1: j
Stream 2: k
Stream 3: l
Stream 0: m
Stream 1: n