c - 如何让这个C函数连续执行?

标签 c

我有一个 C 程序,它从命令行获取输入,处理输入,生成文件并终止。

例如 myprogram.c 类似:

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

//do something with the input
// and generate a file

exit(0);
}

我目前给出的输入为: echo -n abcd | myprogram.c

我希望程序做的不是在一次输入后终止,而是应该继续执行并等待下一个控制台输入以生成下一个文件,依此类推。

有人可以指导我吗?

最佳答案

您可以使用while循环:

#include <stdio.h>
#include <string.h>
#include <stdbool.h>

bool function(char *input)
{
    // do something with the input
    // and generate a file

    // example:
    if (strcmp(input, "exit") == 0)
        return true;

    printf("I did something with '%s'\n", input);
    return false;
}

int main(int argc, char *argv[])
{
    if (argc < 2)
    {
        printf("Usage: program_name <argument>.");
        return 1;
    }

    function(argv[1]);

    bool exit = false;
    while (!exit)
    {
        char input[32];
        scanf("%s", &input);
        exit = function(input);
    }
    return 0;
}

关于c - 如何让这个C函数连续执行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58502687/

相关文章:

C将指针传递给函数混淆

python - PyModule_New 的目的和用法

c - "fork()"后printf异常

c - 如何在 Ruby C API 中获取 VALUE 的类

c - 有没有办法检测文件依赖项何时满足 "accidentally"?

c - Ext2 - 文件是如何创建的

c - 这段c代码中的奇怪行为是什么?

c - 从不兼容的指针类型传递参数 x ...

c - gcc -march= native 。检测为错误架构构建的二进制文件的方法?

c - 在 C 中使用指针操作二维数组