954,492 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

scaning a txt file

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

northrox
Newbie Poster
5 posts since Dec 2011
Reputation Points: 10
Solved Threads: 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;
}
deceptikon
Indubitably
Administrator
632 posts since Jan 2012
Reputation Points: 119
Solved Threads: 105
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You
View similar articles that have also been tagged: