【发布时间】:2021-10-19 21:20:51
【问题描述】:
如何从 C 中的文件中检索浮点值数组?这是我到目前为止使用的代码,但我遇到了分段错误(在我的代码中标记)。如果您看到一种不那么痛苦的方法,那也会有所帮助。
值存储在文件中,每个值后面都有一个空格,如下所示:
-667.0897114275529 544.6798599456312 -148.0586015260273 -323.4504101541069 .
// open file
FILE *fp;
fp = fopen(sig_file, "r");
if (fp == NULL){
printf("File opened incorrectly or is empty");
return 1;
}
// find file size
fseek(fp, 0L, SEEK_END);
long sz = ftell(fp);
fseek(fp, 0L, SEEK_SET);
// store file contents to f_contents
char *f_contents = 0;
f_contents = malloc(sz);
if (f_contents){
fread(f_contents, 1, sz, fp);
}
fclose(fp);
if (f_contents){
// find how many points are in the file
long pt_count = 0;
int i;
for (i=0; i<sz; i++){
if (f_contents[i] == ' '){
pt_count++;
}
}
// store points to a float array
double signal[pt_count];
char *pt;
pt = strtok(f_contents, " ");
// seg fault 11:
if (pt == NULL){
printf("error with pt");
return 1;
}
signal[0] = atof(pt);
//
for (i=1; i<pt_count; i++){
pt = strtok(NULL, " ");
signal[i] = atof(pt);
}
}
free(f_contents);
【问题讨论】:
-
既然你算了有多少分,你不想
float signal[pt_count];和for (i=1; i<pt_count; i++){吗?每次使用前还需要检查strtok返回的指针是否不是NULL。 -
请注意,示例输入包含的数字比
float类型可以表示的精度高得多。你确定不想要doubles 吗? -
为什么不用
fscanf()而不是自己用strtok()和atof()解析文件? -
小提示,不要小看
return的力量。if (!f_contents){ fclose(fp); printf("failed to malloc\n"); return; }此后无需进一步检查f_contents是否有效。
标签: arrays c string file segmentation-fault