如何读取文件和分离值

How Read File And Separate Values

我正在尝试读取这样的文件:

nInp=20
nOut=1
NLaye=3
hid=30
er=0.001
epo=100
epoRep=100
pscpa=0
tip=Aggr
net=emi
numPrec=0.25
prec=NH3;NOX;PM10;SO2;VOC
rag=4

并且我必须只读取 = 之后的值,对于 prec 的值,我必须用新的分隔符分隔每个值(用 ; 分隔)行,然后我将它们写入一个新文件,如:

NH3
NOX
PM10
SO2
VOC

读等号后没有问题,但我无法分开price

这是我的功能:

void settaggiRete(char values[20][50]){
    char line[50]; 
    int i = 0, j = 0;
    char str[10][20];
    FILE *conf = fopen("conf.txt", "r");
    if(conf == NULL){
        printf("Impossibile apripre il file conf\n");
        exit(EXIT_FAILURE);
    }

    //Ciclo sulle linee del file di configurazione
    while(fgets(line, sizeof(line), configRete) != NULL){
//        Leggo i valori contenuti dopo =
        if(i==10){
            char * str = values[10];
            sscanf(line, "%*[^=]=%s", values[i]);
            while ((token = strsep(line, ";")) != NULL){
                str[j] = token; 
                j++;
            }
        }else{
            sscanf(line, "%*[^=]=%s", values[i]);
        }
        i++;
    }
    fclose(configRete);    
}

那么我怎样才能分离这些值呢?

不能像这样给数组赋值

str[j] = token;

尝试

strcpy(str[j], token);

尽管这样做很危险,所以您可以

size_t length = strlen(token);
if (length >= sizeof(str[j]))
    length = sizeof(str[j]) - 1;
memcpy(str[j], token, length);
str[j][length] = '[=12=]';

请注意,您正在以修剪令牌为代价编写安全代码,因此更好的方法是使用动态分配。

你也在循环中重新声明了str,所以删除这一行

char * str = values[10];

这可能是错误的,具体取决于您声明的方式 values

在主要部分分开。
像这样:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void settaggiRete(char values[20][50]){
    char line[50]; 
    int i = 0;
    FILE *conf = fopen("conf.txt", "r");
    if(conf == NULL){
        printf("Impossibile apripre il file conf\n");
        exit(EXIT_FAILURE);
    }

    while(fgets(line, sizeof(line), conf) != NULL){
        sscanf(line, "%*[^=]=%49s", values[i++]);
    }
    fclose(conf);   
}

int main(void){
    char values[20][50] = {{0}};
    char *value11[25];
    int i, v11 = 0;

    settaggiRete(values);
    for(i=0;i<20;i++){
        if(!*values[i])
            break;
        if(i==11){
            char *token, *p = values[11];
            int j = 0;
            while(token = strsep(&p, ";")){
                value11[v11++] = token;
            }
            for(j = 0; j < v11; ++j){
                printf("values[11][%d]=%s\n", j, value11[j]);
            }
        } else {
            printf("values[%d]=%s\n", i, values[i]);
        }
    }

    return 0;
}