2013-03-02 55 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);