简体   繁体   中英

Loop Problem while reading a text file in C

Hi guys i wanna read a text file word by word and count the words while doing it and then pass the words and numbers to my linked list.

But i have a loop problem. I can't escape from the infinite loop.

Here is my code:


int main()
{
    char kelime[100];
    char kelime2[100];
    long a = 0;

    FILE * dosya = fopen("oku.txt", "r");
    
    while(1)
    {
        fseek(dosya,a,SEEK_CUR);
        
        if(feof(dosya))
        {
            break;  
        }
        
        while(fscanf(dosya, "%99[^ \n]", kelime) == 1)
        {
            printf("%s \n",kelime);
            a = ftell(dosya);
        }
        
        while(1)
        {
            fscanf(dosya, "%s" , kelime2);
            printf("%s \n",kelime2);
            
            if((strcmp(kelime, kelime2))== 0)
            {
                // Things to do...
            }
            
            memset(kelime2,0,sizeof(kelime2));
            
            if(feof(dosya))
            {
                rewind(dosya);
                break;
            }
        }
    }
    fclose(dosya);
    
    return 0;
}

To read any kind of space-delimited word, all you need is something like:

while (fscanf(dosya, "%99s", kelime) == 1)
{
    // Do something with the "word" in kelime
}

The scanf family of functions all return the number of conversions it successfully made. With a single conversion specifier it can only return 1 on success, 0 if the specifier could not be matched (should never happen in this case) or -1 on error or end of file.

The loop will simply read all words in the input file until the end of the file.

Putting it together in a program that reads and print all words, it would look something like this:

#include <stdio.h>
#include <stdlib.h>

int main(void)
{
    FILE *dosya = fopen("oku.txt", "r");
    if (dosya == NULL)
    {
        perror("Could not open file");
        return EXIT_FAILURE;
    }

    char kelime[100];
    size_t counter = 0;

    while (fscanf(dosya, "%99s", kelime) == 1)
    {
        printf("Read word #%zu: %s\n", ++counter, kelime);
    }

    fclose(dosya);

    printf("There was a total of %zu \"words\" in the file\n", counter);
}

A little explanation for the %zu format specifier for printf :

The u is the base format (it's really %u ), and stands for u nsigned integer. The z prefix tells printf that the corresponding argument is really a size_t value.

The type size_t is a standard C type that is used for all kinds of sizes, counters and indexes. It's an unsigned integer of unspecified size.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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