We're a community of 1076K IT Pros here for help, advice, solutions, professional growth and fun. Join us!
1,075,608 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Start New Discussion Reply to this Discussion

scaning a txt file

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

2
Contributors
1
Reply
13 Minutes
Discussion Span
1 Year Ago
Last Updated
2
Views
northrox
Newbie Poster
7 posts since Dec 2011
Reputation Points: 10
Solved Threads: 0
Skill Endorsements: 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
Challenge Accepted
Administrator
3,426 posts since Jan 2012
Reputation Points: 822
Solved Threads: 473
Skill Endorsements: 56

This article has been dead for over three months: Start a new discussion instead

Post: Markdown Syntax: Formatting Help
 
You
View similar articles that have also been tagged:
 
© 2013 DaniWeb® LLC
Page rendered in 0.2853 seconds using 2.67MB