1,105,636 Community Members

scaning a txt file

Member Avatar
northrox
Newbie Poster
7 posts since Dec 2011
Reputation Points: 0 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]
 
0
 

how do i scan a specific int in a txt file.

Member Avatar
deceptikon
Eternally Awesome
4,700 posts since Jan 2012
Reputation Points: 1,341 [?]
Q&As Helped to Solve: 690 [?]
Skill Endorsements: 104 [?]
Administrator
Featured
 
0
 

It all depends on how the file is formatted and how deeply you want to scan. If the int is a word of its own and not part of a larger word, you can just read words and check for the int:

#include <stdbool.h>
#include <stdio.h>

bool is_int(char const* s, int* value)
{
    // Fill in this function. strtol() is a good start for testing for int.
}

int main(void)
{
    FILE* fp = fopen("file", "r");

    if (fp)
    {
        char word[BUFSIZ];
        int needle = /* The int being searched */;

        while (fscanf(fp, "%s", word) == 1)
        {
            int value;

            if (is_int(word, &value) && value == needle)
            {
                puts("FOUND");
                break;
            }
        }

        fclose(fp);
    }

    return 0;
}
You
This article has been dead for over three months: Start a new discussion instead
Post:
Start New Discussion
View similar articles that have also been tagged: