[英]Number of letters in a text file
在程序的這一部分中,我想讀取一個文本文件並將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;
}
您正在丟棄其他所有字符,因為每次循環迭代都調用fgetc
兩次。
更改此:
while(fgetc(fileA) != EOF) {
holder = fgetc(fileA);
對此:
while((holder = fgetc(fileA)) != EOF) {
只需打開文件並獲取它的大小即可。 跳過任何內存分配和字符讀取...
FILE *f = fopen(fn, "r");
fseek(f, SEEK_END, 0);
long int lenA = ftell(f);
fclose(f);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.