2012-01-14 63 views
1

我想問一下爲什麼這段代碼導致了分段錯誤。我試圖從文本文件中獲取輸入,但我無法弄清楚問題所在。文件訪問中的分段錯誤

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; 
} 
+1

確定50個字符就夠了?另外,如果trainfile == NULL,那麼你調用fclose(NULL) – slezica 2012-01-14 14:37:04

回答

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 
3
int k, n, maxval1, maxval2, classnum; 
char dataArray[n][3]; 

n沒有初始化,所以它可以是任何值,因此你的代碼中有一個未定義行爲

err ...它沒有用過。

在代碼中的另一個問題是你的數據緩衝區:

char str[50]; 

應該大到足以容納該文件的內容,它有可能是不和導致未定義行爲

+0

'str'不需要保存整個文件,一般來說,只是連續非空白字符的最長序列。如果文件是英文純文本,則50可能就足夠了。但是有段錯誤,所以文件可能不是。 – 2012-01-14 15:58:51