【问题标题】:How to get commands from file redirection?如何从文件重定向中获取命令?
【发布时间】:2019-12-05 02:29:49
【问题描述】:

我正在尝试从包含需要传递给我的程序的命令的输入文件中获取信息。当我执行 C 文件时,我使用./inventory test01/inventory01-actual.txt < test01/input01.txt > test01/actual01.txt。包含命令的文件是 input-01.txt。比如input-01.txt的内容如下:

PRINT
QUIT

如下面的代码所示,第一个 while 循环遍历文件 test01/inventory01-actual.txt 并解析输入。当我调用scanf 时,它只读取第一个命令(PRINT)然后程序终止。我知道我需要一个 while 循环来让它通过并读取输入文件中的每个命令,但我不确定如何在我的代码中引用它。

我也想过

while (______ ! EOF) {
.... 
}

...但我不确定要在空白处填写什么以引用 input-01.txt。我可以使用feof 之类的东西吗? (当然,我会将scanf 和 if-else 语句放在这个 while 循环中)。

FILE *src_file;

src_file = fopen(argv[1], "r");
//Initialize data for node
int id; 
char name[MAX_NAME];
char summary[MAX_SUM];
int count;

char buffer[MAX_LEN_COMMAND];

//Parse file input line by line
while (fgets(buffer, sizeof(buffer), src_file) != NULL) {
    if (sscanf(buffer, "%d, %[^,], %[^,], %d\n", &id, name, summary, &count) == INPUT_COUNT) {
        if (count < 0) {        
            printf("Invalid count value.");         
            exit(EXIT_BAD_INPUT);    
        }
        if (isEmpty(summary) || isEmpty(name)) {
            //Skip this iteration
            printf("RECORD NOT INSERTED\n");
            continue;
        }
        printf("RECORD INSERTED: %d\n", id);
        //Add each struct to the linked list      
        addRecord(list, id, name, summary, count); 
    } else {
        printf("RECORD NOT INSERTED\n");  
    }
}

//Get user input for commands    
char command[MAX_LEN_COMMAND];

//Keep re-prompting user for commands until you reach EOF  
printf("====================\nCommand? ");    
scanf("%s", command);    
if (strcmp(command, "PRINT") == 0) {     
    print(list);     
} else if (strcmp(command, "QUIT") == 0) {
    quit(argv[1], list);
    exit(EXIT_SUCCESS);   
} else {
    printf("Invalid command passed.\n"); 
    exit(EXIT_BAD_INPUT);
}

我的目标是让我的程序读取 input-01.txt 文件中的每个命令,而我的程序目前只读取该文件的第一行。

【问题讨论】:

标签: c while-loop io stream user-input


【解决方案1】:

所以现在的问题是当你调用 scanf("%s", ...).使用一个 %s 作为格式说明符,scanf() 将读取第一个字符串,直到找到包含新行的空格。如果你有 scanf("%s %s", command1, command2) 你会得到想要的结果。

但是,您可能希望您的代码在输入文件中的命令数量方面更具可扩展性。在这种情况下,我建议使用 fgets()。

  //Get user input for commands    
  char command[MAX_LEN_COMMAND];
  while(fgets(command, sizeof(command), stdin) != NULL)
  {
    /* Do whatever you have to do with command */
  }

还要小心,您是在直接将命令与某些字符串进行比较。确保您的输入文件的每一行都没有任何尾随空格。

【讨论】:

    猜你喜欢
    • 2011-08-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-19
    • 2020-03-24
    • 2010-09-16
    • 2014-05-10
    相关资源
    最近更新 更多