mahdimb
mahdimb

Reputation: 139

Number of letters in a text file

In this part of program I want read a text file and give length of string in txt file into lenA, but when str1.fa included 10, program output 5, for 6 character shown 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;
}

Upvotes: 0

Views: 98

Answers (2)

V-X
V-X

Reputation: 3029

just open the file and get it's size. skip any allocation of memory and reading of characters...

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

Upvotes: 1

Paul R
Paul R

Reputation: 212979

You are discarding every other character because you are calling fgetc twice per loop iteration.

Change this:

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

to this:

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

Upvotes: 2

Related Questions