我正在尝试读取这样的文件:
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] = '\0';
请注意,您正在以修剪 token 为代价编写安全代码,因此更好的方法是使用动态分配。
你也在循环内重新声明了str
,所以删除这一行
char * str = values[10];
根据您声明 values
的方式,这可能是错误的。
关于c - 如何读取文件和分离值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29087092/