我有一个看起来像这样的文本文件:
NAME=Myname //string without ""
文本文件是系统文件 我无法更改文件,无法在变量中添加 "
我的问题:如何读取 C 中的变量?
谢谢。
使用fgets()/sscanf()
并检查结果。
FILE = fopen("text_file.txt, "r");
...
char buffer[100];
char VarName[sizeof buffer];
char VarValue[sizeof buffer];
if (fgets(buffer, sizeof buffer, inf) == NULL)
Handle_EOForIOerror();
if (sscanf(buffer, "%[^n=]=%[^n]", VarNae, VarValue) != 2)
Handle_FormatError();
else
Sucess();
...
fclose(inf);
您可以使用如下所示的代码来读取此示例文件
char *key, *value;
FILE *fh;
fh = open("...", "r");
/* error check */
while (fscanf("%m[^=]=%ms", &key, &value) == 2) {
/* process key and value */
/* free key and value when you do not need them anymore */
free(key);
free(value);
}
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
typedef struct var {
char *var_name;
char *value;
} Var;
int main() {
char line[128];
FILE *fp = fopen("data.txt", "r");
char *p, *pp;
Var var;
fgets(line, sizeof(line), fp);
fclose(fp);
p = line;
pp = NULL;
//delete comment
while(NULL!=(p=strstr(p, "//"))){
pp = p;
p += 2;
}
if(pp != NULL)
*pp = ' ';
else
pp = strchr(line, ' ');
//trim end
while(isspace(pp[-1]==' '))
*--pp = ' ';
p=strchr(line, '=');
var.var_name = malloc( p - line +1);
*p=' ';//split
strcpy(var.var_name, line);
pp = strchr(p, ' ');
var.value = malloc(pp - p);
strcpy(var.value, p+1);
printf("%s="%s";n", var.var_name, var.value);
//free
return (0);
}