类似于 ' Loading Variables from Text File in C++ ' 但在 C 而不是 C++ 中
我想要一个充当网络服务器的主程序,然后是加载变量的 webserver.conf 文件。基本上 webserver.conf 将确定 Web 服务器的行为方式(例如,当收到 GET 请求时)
变量如
hostname = 127.0.0.1
port = 80
等...
我了解 fopen fclose 的概念和用于读取文件的基本 C 函数,但仍在学习这些并且我在网上找不到太多关于从文件读取和设置变量的信息。
任何人都可以提供一个非常简单的示例,其中 C 程序在下面以 super 简单的文件 fopen 开始。
int main(void) {
FILE *fp;
char *mode = "r";
fp = fopen("/home/lewis/Documents/config/webconfig.conf", mode);
if (fp == NULL) {
fprintf(stderr, "Can't open input file webconfig.conf!\n");
exit(1);
return (EXIT_SUCCESS);
}
}
上下文是我想使用 GET 命令然后打印结果(配置文件)
抱歉,目的似乎有偏差......我会尝试应用逻辑......
main web server
loads webconfig (should be default file to load for GET) to set internal variables
determines action for receiving a GET command
receieves GET command from keyboard
Checks file that is requested
opens file, reads contents
prints contents to stdout
我知道每个不同的功能、文件处理、输入处理等都会有多个文件......
只需要在正确的方向上稍微插入一下学习和全神贯注。
**** 不需要代码,只需了解逻辑和理解如何将这样的 C 程序组合在一起*****
谢谢
最佳答案
以前只是打开文件描述符,您需要从文件中解析值。
这是一个配置文件示例:
hostname 127.0.0.1
port 8080
下面是如何解析它的代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct
{
char *addr;
int port;
} MainStruct;
int parse_config(MainStruct * inf)
{
/* Used variables */
FILE *file;
char * line = NULL;
char *addr;
size_t len = 0;
ssize_t read;
/* Open file pointer */
file = fopen("config.conf", "r");
if(file != NULL)
{
/* Line-by-line read cache file */
while ((read = getline(&line, &len, file)) != -1)
{
/* Find key in file */
if(strstr(line, "hostname") != NULL)
{
/* Get addres */
inf->addr = strdup(line+8);
}
if(strstr(line, "port") != NULL)
{
/* Get port */
inf->port = atoi(line+4);
}
}
/* Close file */
fclose(file);
} else return 0;
return 1;
}
int main()
{
/* Used variables */
MainStruct val;
int status;
/* Parse congig */
status = parse_config(&val);
/* Check status */
if (status) printf("File parsed succssesfuly\n");
else printf("Error while parsing file\n");
/* Print parsed values */
printf("Port: %d\n", val.port);
printf("Addr: %s\n", val.addr);
}
您可以运行函数 parse_config() 并给出 MainStruct 结构变量的参数,如下所示:
MainStruct val;
parse_config(&val)
printf("Hostname: %s\n", val.addr);
printf("Port: %d\n", val.port);
主机名和端口的变量将保存在MainStruct结构变量中。
输出将是:
Port: 8080
Addr: 127.0.0.1
此外,我还编写了简单的非阻塞 Web 服务器 shttpd: https://github.com/kala13x/shttpd
您可以检查并使用它,ih 有 conf 文件“config.cfg”,我使用 inih 解析器从配置中解析值。您可以下载检查并编译以查看其工作原理。希望这个回答对你有用
关于Web服务器在C中接收GET请求的配置文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29431081/