输入重定向和倒带

时间:2013-04-21 14:57:49

标签: c

我正在将文本文件重定向到我的C程序,例如

./test.c < earthquakes.txt

我用scanf读取了我需要的数据:

while (scanf("%4d-%2d-%2d%c%2d:%2d:%2d+%2d:%2d,%f,%f,%f,%f",
    &yyyy, &mm, &dd, &junkc, &hh, &min, &sec, &junki, &junki,
    &latit, &longi, &depth, &magnitude) == 13) {
    printf("test\n");
    num_earthquakes++;
}

直到我读完了我需要的所有行。在这之后,我如何回退到stdin的开始?

3 个答案:

答案 0 :(得分:2)

stdin是一个流而不是常规文件,所以你不能只是回滚输入。

所以我想,您应该使用该文件的常规读取,或者如果您想将接收的数据复制到缓冲区,以便再次读取它。

答案 1 :(得分:1)

或许进行一次传递是最佳选择:读取值,并在必要时使用realloc调整数组大小。为了最大限度地减少大量输入错误的可能性,您只需存储所需信息即可解决问题。如果输出基于月份,则根据月份收集信息。例如:

size_t count = 0;
struct month_stat *month = NULL;
while (count <= SIZE_MAX / sizeof *month &&
       scanf("%4d-%2d-%2d%c%2d:%2d:%2d+%2d:%2d,%f,%f,%f,%f",
             &yyyy, &mm, &dd, &junkc, &hh, &min, &sec, &junki, &junki,
             &latit, &longi, &depth, &magnitude) == 13)
{
    /* resize based upon powers of two for simplicity */
    if (count & (count - 1) == 0)
    {
        void *temp = realloc(month, (count * 2 + 1) * sizeof *month);
        if (temp == NULL)
        {
            /* handle error */
        }

        month = temp;
    }

    /* TODO: Update month[count] and overall stats
     *       When the month changes, you'll want to count++;
     */
}

您是否知道可以通过在*和您使用的任何格式说明符之间放置%来告诉scanf放弃输入?例如,assert(scanf("%*c") == 0);将读取并丢弃没有赋值的字符,这反映了返回值。

答案 2 :(得分:0)

一种可能的方法是在第一次演讲中建立一种记忆中的表现形式。例如,您创建对应于每一行的链接列表,该元素是您自己的结构。

这样,只要一次又一次地阅读,你就会有一种有趣且方便的方式来使用它们。