【问题标题】:How to read data from stdin mutiple times in C program如何在C程序中多次从stdin读取数据
【发布时间】:2016-05-18 09:25:26
【问题描述】:

我正在用 C 语言编写一个程序来解决迷宫游戏。输入迷宫文件将从标准输入读取。我写了下面的程序,它从标准输入读取迷宫并打印没有。行和列。但是,一旦我完全阅读了我的输入文件,我怎样才能再次访问它以便我可以执行接下来的步骤?

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

#define BUFFERSIZE (1000)


struct maze {
    char ** map;
    int startx, starty;
    int numrows;
    int initdir;
};

void ReadMaze(char * filename, struct maze * maze);

int main(int argc, char *argv[]) {
    struct maze maze;


    ReadMaze(argv[1], &maze);

    return EXIT_SUCCESS;
}


/*  Creates a maze from a file  */

void ReadMaze(char * filename, struct maze * maze) {
    char buffer[BUFFERSIZE];
    char mazeValue [BUFFERSIZE][BUFFERSIZE];
    char ** map;
    int rows = 0, foundentrance = 0, foundexit = 0;
    int columns = 0;

    /*  Determine number of rows in maze  */


    while ( fgets(buffer, BUFFERSIZE, stdin) ){
       ++rows;
       puts(buffer);
       columns = strlen(buffer);

    }

    printf("No of rows:  %d\n", rows);
    printf("No of columns: %d\n", columns);

    if ( !(map = malloc(rows * sizeof *map)) ) {
        fputs("Couldn't allocate memory for map\n", stderr);
        exit(EXIT_FAILURE);
    }

}

【问题讨论】:

  • 你能改变文件的格式,以迷宫大小的两个值(宽度和高度)开头,然后是迷宫数据吗?这样,您只需对文件进行一次传递。

标签: c pointers struct


【解决方案1】:

您必须在阅读时将其存储在缓冲区中。一旦你读过stdin,你就不能倒带和/或再读一遍。

【讨论】:

  • Angew 你能帮我理解如何将数据存储到缓冲区中。
  • 我的迷宫文件是这样的
    #.#######
    #.......#
    ####.## ##
    #....#..#
    #.####.##
    中间没有空格
  • 我会直接将其转储到 char * 缓冲区中。抱歉,我的 C 有点生锈了
【解决方案2】:

如果要再次读取文件,可以使用rewind

FILE * fp;

// Open and read the file

rewind(fp);

// Read it again

fclose(fp);

但是,对于 stdin,这是行不通的。您必须存储从stdin 读取的内容。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-03-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-07
    • 1970-01-01
    相关资源
    最近更新 更多