我有一个看起来像这样的文本文件:
NAME=Myname //string without ""
文本文件是系统文件我无法更改文件,我无法在变量中添加“”
我的问题: 如何读取C中的变量?
感谢。
答案 0 :(得分:1)
您可以使用以下代码来阅读此示例文件
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);
}
答案 1 :(得分:1)
使用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);
答案 2 :(得分:0)
#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 = '\0';
else
pp = strchr(line, '\0');
//trim end
while(isspace(pp[-1]==' '))
*--pp = '\0';
p=strchr(line, '=');
var.var_name = malloc( p - line +1);
*p='\0';//split
strcpy(var.var_name, line);
pp = strchr(p, '\0');
var.value = malloc(pp - p);
strcpy(var.value, p+1);
printf("%s=\"%s\";\n", var.var_name, var.value);
//free
return (0);
}