gpt4 book ai didi

c - 如何从文件中读取命令并在 c 中执行这些命令?

转载 作者:行者123 更新时间:2023-12-04 05:30:38 25 4
gpt4 key购买 nike

假设我有一个这样的文件:

rotate -45
move 30

哪里 rotatemove是我写的两个函数。
但我正在从文本文件中读取这些内容。

那么,我如何才能将这些用作我的程序的命令?

我正在考虑使用 strcmp ,例如。因此,我会将我读取的字符串与我所知道的可能命令进行比较。然后,如果它们匹配,我想调用请求的函数。

我真的很想看一些示例代码来帮助理解。

谢谢你的提示。
所以使用 brunobeltran0 的第一种方法,我会做这些:
        char*next_command;
char* get_next_command;g = fopen("b", "r");/*b is the name of the file*/

while(!feof(g))
{
get_next_command=fgetc(g);

next_command = strtok(get_next_command, " ");

while (next_command != NULL) {

printf("%s\n", next_command);

next_command = strtok(NULL, " ");

if (!strcmp(next_command, "rotate"))
{

rotate (/*how would I get the number to be in here*/ )


}`

这看起来不对。我错过了理解你们吗?

最佳答案

我将假设您的意思是您想要编写一个程序,该程序在给定一个包含它可以理解的命令的输入文件的情况下,从所述输入文件中读取并执行这些命令。
根据你有多少命令,以及你对这些函数的格式的了解,周围的代码可能会有明显的不同,但在一般情况下,逻辑将类似于(忽略内存管理) )

char *next_command = get_next_command(...); // reading the commands is really specific to the input you expect
if (!strcmp(next_command, "some_command"))
{
void *param_arr[PARAM_CNT_FOR_SOME_COMMAND] = get_params_for_some_command();
some_command(param_arr[0], param_arr[1], param_arr[2]); // assume some_command takes 3 arguments
}
else if (!strcmp(next_command, "some_other_command"))
...

例如,如果你想旋转 -45,
char *next_command = get_next_command(...); // reading the commands is really specific to the input you expect
if (!strcmp(next_command, "rotate"))
{
void *param_arr[1] = get_rotation_angle();
rotate((int *)param_arr[0]); // assume some_command takes 3 arguments
}

应该工作。

如果您有可用的映射,那么从可能的输入命令映射到它们各自的函数并允许函数从文件本身读取以查找其参数可能会更有效。

例如:
char *next_command = get_next_command(file_pointer);
(*get_func_pointer(next_command))(file_pointer); // where get_func_pointer is a function that
// returns the function pointer assoc. with 'next_command'
/* somewhere else in the code */
void func_returned_by_get_func_pointer(FILE *fp)
{
read_params_from(fp);
do_everything_as_usual();
}

关于c - 如何从文件中读取命令并在 c 中执行这些命令?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12670159/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com