-2

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.

doptimusprime
  • 9,115
  • 6
  • 52
  • 90
David B
  • 1
  • 1
  • 1

3 Answers3

1

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);
}
Lee Duhem
  • 14,695
  • 3
  • 29
  • 47
1

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);
chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256
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);
}
BLUEPIXY
  • 39,699
  • 7
  • 33
  • 70