在這部分程序中,我希望讀取一個文本文件並將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;
}
看起來像C++給我。 – cnicutar 2013-03-02 11:23:28
@cnicutar我在想什麼 - 它是帶C('free','realloc')的C++語法('namespace')... – 2013-03-02 11:26:16
如果你只是想要文件的大小,你應該'stat'它。 PS永遠不要使用「系統」呼叫! – 2013-03-02 11:46:17