简体   繁体   中英

Reading variables from a TXT file with C

I have a text file that looks like this:

NAME=Myname //string without ""

The text file is a system file I can't change the file, I can't add "" to the variable

My question: How can I read the variables in C?

Thanks.

You could use some code like the following to read this sample file

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);
}

Use fgets()/sscanf() and check results.

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);
#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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM