【发布时间】:2017-03-31 14:51:42
【问题描述】:
所以我试图从文本文件中读取并将其放入变量中
在文本文件中有
NAME= Bame
GAME= Fame
我听说过 strsep/strtok,但我仍然遇到问题,使用此代码我得到 Segmentation Fault 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];。另见Why is “while ( !feof (file) )” always wrong?。因此,请将您的feof替换为您的fgets。 -
fp = fopen(file, "r"); if (fp == NULL) { perror(Error opening file: "); return 1;}