简体   繁体   English

文本文件中的字母数

[英]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. 在程序的这一部分中,我想读取一个文本文件并将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;
}

You are discarding every other character because you are calling fgetc twice per loop iteration. 您正在丢弃其他所有字符,因为每次循环迭代都调用fgetc两次。

Change this: 更改此:

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

to this: 对此:

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

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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM