文件访问中的分段错误
问题描述:
我想问一下为什么这段代码导致了分段错误。我试图从文本文件中获取输入,但我无法弄清楚问题所在。文件访问中的分段错误
using namespace std;
using namespace cv;
int main()
{
char str[50];
FILE *trainfile;
int k, n, maxval1, maxval2, classnum;
char dataArray[n][3];
trainfile = fopen("training.txt", "r+");
if(trainfile == NULL){
perror("Cannot open file.\n");
}else{
while(!feof(trainfile)){
fscanf(trainfile, "%s", str);
}
}
fclose(trainfile);
return 0;
}
答
一个问题是您的缓冲区可能不够大。
您应该首先获取文件的大小,然后制作一个具有该大小的动态缓冲区,然后最终读取该文件。
fseek(trainfile,0,SEEK_END); //Go to end
int size = ftell(trainfile); //Tell offset of end from beginning
char* buffer = malloc(size); //Make a buffer of the right size
fseek(ftrainfile,0,SEEK_SET); //Rewind the file
//Read file here with buffer
答
int k, n, maxval1, maxval2, classnum;
char dataArray[n][3];
n
没有初始化,所以它可以是任何值,因此你的代码中有一个未定义行为。
err ...它没有用过。
在代码中的另一个问题是你的数据缓冲区:
char str[50];
应该大到足以容纳该文件的内容,它有可能是不和导致未定义行为。
+0
'str'不需要保存整个文件,一般来说,只是连续非空白字符的最长序列。如果文件是英文纯文本,则50可能就足够了。但是有段错误,所以文件可能不是。 – 2012-01-14 15:58:51
确定50个字符就够了?另外,如果trainfile == NULL,那么你调用fclose(NULL) – slezica 2012-01-14 14:37:04