【发布时间】:2016-04-07 19:14:50
【问题描述】:
我创建了一个代码,该代码将使用 C 将 .txt 文件解析为双精度数组。我的 .txt 文件已格式化,因此每个点都由 "," 分隔。现在我想让这段代码解析相同的数据,但来自 .csv 文件。当我更改文件类型时,我收到分段错误。
为什么会发生这种情况?我是否误以为这两种文档类型将以相同的方式阅读?
这篇文章的主要问题是,读取 .txt 和 .csv 有什么区别?
/*
* Calibration File Read Test
*/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main ()
{
FILE *myfile = fopen ( "BarEast.txt", "r" );
/* I want to change this file type to .csv */
/* opening file for reading */
if(myfile == NULL)
{
printf("Error opening file");
return(-1);
}
int i = 0;
int j, k;
char *result[361] = {0};
char line[10];
char *value;
while(fgets(line, sizeof(line), myfile))
{
value = strtok(line, ",");
result[i] = malloc(strlen(value) + 1);
strcpy(result[i], value);
i++;
}
double val;
double cal[361] = {0};
for(k = 0; k < 361; k++)
{
val = atof(result[k]);
cal[k] = val;
}
for(j = 0; j < 361; j++)
{
printf("Element[%d] = %f\n", j, cal[j]);
}
fclose(myfile);
return 0;
}
【问题讨论】:
-
只需使用
sscanf从支持某种正则表达式的字符串中扫描,请阅读此处:cplusplus.com/reference/cstdio/scanf -
我建议您比较您的 .txt 和 .csv 文件。我认为除了文件扩展名之外,它们在所有方面都应该相同,如果您的代码适用于其中一个,它应该适用于另一个。
-
Don't use Strcpy 如果您阅读了man page for strcpy 中的注释,就会明白为什么要远离它。
-
问题不在于更改文件名,问题更确定,因为您的代码存在内存问题,这些问题由 .csv 文件的不同内容揭示。使用
valgrind或类似工具来找到它们。