基本上,我有此功能,它可以计算文本文件中的行数,这让我很头疼。它像带有小文件的魅力一样工作(例如,具有50000行)。但是,由于某些原因,当我尝试对具有100万行的文件中的行进行计数时,会出现分段错误错误。这是代码:
int countlines(char *filename)
{
// count the number of lines in the file called filename
FILE *fp = fopen(filename,"r");
int ch=0;
int lines=0;
if (fp == NULL)
return 0;
while ((ch = fgetc(fp)) != EOF)
{
if (ch == '\n')
lines++;
}
fclose(fp);
return lines;
}
老实说,我已经尝试了千种变化,但我不知道出了什么问题。它达到了1000000的行数,但是却给了我一个Segmentation Fault错误。任何帮助将不胜感激!
编辑:既然每个人都说它对他们有用,那么我将向您展示主要功能中的内容。
int main(int argc, const char * argv[])
{
int X_len = countlines("/homes/myworkspace/X.txt");
int X[X_len][4];
printf("\n X_len = %d",X_len);
}
这就是问题
int X[X_len][4];
X_len大于1000000时,您没有足够的内存用于(堆栈)数组。
尝试动态分配(堆),而不是
int (*X)[4];
X = malloc(X_len * sizeof *X);
if (X == NULL) /* error */;
// ...
free(X);
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句