0
,所以我想从一个文本文件中读取并把它放在一个变量从文件读取一个配置
在文本文件中有
NAME= Bame
GAME= Fame
我听说strsep /的strtok的但我仍然有问题,以及与此代码我得到分割故障11
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
int main() {
char *token;
char *string;
char *tofree;
FILE *fp;
const char *file = "/tmp/test.txt";
fp = fopen(file, "r");
while(!feof(fp)) {
fgets(string, sizeof(string), fp);
token = strsep(&string, ",");
printf("%s", string);
}
fclose(fp);
exit(0);
}
'char * string;'是_不是一个字符串。它是一个指向“char”的指针,指向“无处”,因为它没有被初始化。你写入这个未初始化的指针,从而调用UB。因此,崩溃。通过使用字符数组修复:'char string [100];'。另请参阅[为什么“while(!feof(file))”总是错误?](http://stackoverflow.com/questions/5431941/why-is-while-feof-file-always-wrong)。所以,用你的'fgets'替换你的'feof'。 –
'fp = fopen(file,“r”); if(fp == NULL){perror(Error opening file:“); return 1;}' – LPs
另请参见[为什么while(!feof(file))总是出错?](http://stackoverflow.com/questions/5431941 /为什么 - 是 - 同时-FEOF文件 - 总是错的) –