2013-03-02 52 views
0

在這部分程序中,我希望讀取一個文本文件並將txt文件中的字符串長度變爲lenA,但是當str1.fa包含10時,程序輸出5將顯示6個字符3。文本文件中的字母數

#include <iostream.h> 
    #include <stdio.h> 
    using namespace std; 

    int main(){ 
int lenA = 0; 
FILE * fileA; 
char holder; 
    char *seqA=NULL; 
char *temp; 

//open first file 
fileA=fopen("d:\\str1.fa", "r"); 

//check to see if it opened okay 
if(fileA == NULL) { 
    perror ("Error opening 'str1.fa'\n"); 
    exit(EXIT_FAILURE); 
} 

//measure file1 length 
while(fgetc(fileA) != EOF) { 
    holder = fgetc(fileA); 
    lenA++; 
    temp=(char*)realloc(seqA,lenA*sizeof(char)); 
    if (temp!=NULL) { 
     seqA=temp; 
      seqA[lenA-1]=holder; 
    } 
    else { 
     free (seqA); 
     puts ("Error (re)allocating memory"); 
     exit (1); 
    } 
} 
cout<<"len a: "<<lenA<<endl; 
free(seqA); 
fclose(fileA); 

    system("pause"); 
return 0; 
} 
+3

看起來像C++給我。 – cnicutar 2013-03-02 11:23:28

+1

@cnicutar我在想什麼 - 它是帶C('free','realloc')的C++語法('namespace')... – 2013-03-02 11:26:16

+1

如果你只是想要文件的大小,你應該'stat'它。 PS永遠不要使用「系統」呼叫! – 2013-03-02 11:46:17

回答

2

你放棄所有其他字符,因爲你在每個循環迭代調用fgetc兩次。

更改此:

while(fgetc(fileA) != EOF) { 
    holder = fgetc(fileA); 

這樣:

while((holder = fgetc(fileA)) != EOF) { 
+0

它工作。謝謝你:-) – mahdimb 2013-03-02 11:32:19

1

只需打開該文件,並得到它的大小。跳過任何分配的內存和讀取字符...

FILE *f = fopen(fn, "r"); 
fseek(f, SEEK_END, 0); 
long int lenA = ftell(f); 
fclose(f);