Thread: Ignoring most information from File.

  1. #1
    Registered User
    Join Date
    Dec 2014
    Location
    Czech Republic
    Posts
    36

    Question Ignoring most information from File.

    Hello everyone. I have something like this in file.

    Code:
    08.12.2014 #238
    country|currency|quantity|code|course
    Austrálie|dolar|1|AUD|18,668
    Brazílie|real|1|BRL|8,692
    Bulharsko|lev|1|BGN|14,116
    Čína|renminbi|1|CNY|3,649
    Dánsko|koruna|1|DKK|3,711
    EMU|euro|1|EUR|27,610
    Filipíny|peso|100|PHP|50,384
    Hongkong|dolar|1|HKD|2,906
    Chorvatsko|kuna|1|HRK|3,600
    Indie|rupie|100|INR|36,391
    Indonesie|rupie|1000|IDR|1,824
    Izrael|šekel|1|ILS|5,639
    Japonsko|jen|100|JPY|18,600
    Jihoafrická rep.|rand|1|ZAR|1,955
    Jižní Korea|won|100|KRW|2,019
    Kanada|dolar|1|CAD|19,683
    Litva|litas|1|LTL|7,996
    Maďarsko|forint|100|HUF|9,007
    Malajsie|ringgit|1|MYR|6,445
    Mexiko|peso|1|MXN|1,566
    MMF|SDR|1|XDR|32,708
    Norsko|koruna|1|NOK|3,138
    Nový Zéland|dolar|1|NZD|17,217
    Polsko|zlotý|1|PLN|6,636
    Rumunsko|nové leu|1|RON|6,215
    Rusko|rubl|100|RUB|42,072
    Singapur|dolar|1|SGD|17,042
    Švédsko|koruna|1|SEK|2,967
    Švýcarsko|frank|1|CHF|22,965
    Thajsko|baht|100|THB|68,151
    Turecko|lira|1|TRY|9,879
    USA|dolar|1|USD|22,524
    Velká Británie|libra|1|GBP|35,192
    It's conversion between one currency to other and I don't know how i have ignoring all information except (quantity, course, and code), the others are irrelevant. And also ignoring these wierd chars '|'.

    Something like this: quantity: 1 1 1 1 1 ... etc
    code : AUD BRL BGN ... etc
    course : 18,668 8,692 14,116 ... etc
    From file, other information ignoring.

    And please try to explain it to me some examples for better understanding.

    Thx for helped to me.

  2. #2
    Registered User
    Join Date
    Jun 2014
    Posts
    79
    You can try reading one line at a time with fgets(), then parsing that single line using | as a separator (easier than parsing the whole file at once).

  3. #3
    Registered User
    Join Date
    Jun 2005
    Posts
    6,815
    Open the file. Read one line at a time, using a standard function like fgets(). Pick out the information you need and use it as needed. You don't need to do anything else, since reading the next line will implicitly discard the information you don't need.

    Remember to check every operation to see if it succeeds. No point in trying to read a file if opening failed. No point in trying to pick information after a failure to read.
    Right 98% of the time, and don't care about the other 3%.

    If I seem grumpy or unhelpful in reply to you, or tell you you need to demonstrate more effort before you can expect help, it is likely you deserve it. Suck it up, Buttercup, and read this, this, and this before posting again.

  4. #4
    Registered User
    Join Date
    Dec 2014
    Location
    Czech Republic
    Posts
    36
    Quote Originally Posted by aldo_baldo View Post
    You can try reading one line at a time with fgets(), then parsing that single line using | as a separator (easier than parsing the whole file at once).
    It's good idea but how parsing that char | as separator. I'm not sure that i understand you.

  5. #5
    Registered User
    Join Date
    Dec 2014
    Location
    Czech Republic
    Posts
    36
    Quote Originally Posted by grumpy View Post
    Open the file. Read one line at a time, using a standard function like fgets(). Pick out the information you need and use it as needed. You don't need to do anything else, since reading the next line will implicitly discard the information you don't need.

    Remember to check every operation to see if it succeeds. No point in trying to read a file if opening failed. No point in trying to pick information after a failure to read.
    All have but i don't know how pick needed info. Could you write some example?

  6. #6
    Registered User
    Join Date
    Sep 2014
    Posts
    364
    I suggest you to look up the function 'strtok()': strtok - C++ Reference

    But you have special characters i the file that are not included in lower ASCII table.
    So i suggest to use wide character strings (wcs) to not run in problems.
    To use wide character strings make sure to #include <wchar.h>.
    With wcs you have the same functions as with strings (str).

    Here is a comparison of str to wcs:
    The type of variable: char <-> wchar_t
    Format specifier for array: %s <-> %ls
    Format specifier for character: %c <-> %lc

    Funktions:
    fgets <-> fgetws
    strlen <-> wcslen
    strcpy <-> wcscpy
    strcmp <-> wcscmp
    strtok <-> wcstok


    I would read the file line by line with 'fgetws()' and than tokenizing with 'wcstok()' on wide character L'|'.
    This are only my ideas. You can also use normal strings, but i don't know if it works pretty well with the special characters.
    Other have classes, we are class

  7. #7
    Registered User
    Join Date
    Jun 2014
    Posts
    79
    For the sake of fun (I play with code, I'm not professional at all) tried to put together a complete solution of some sort but I fear that the moderators here could classify it as "spoon feeding"...

    Moderators, can I post it so that you can tell me if it is correct?

    Oh, it doesn't make use of wchars, nor it uses strtok().

  8. #8
    Registered User
    Join Date
    Dec 2014
    Location
    Czech Republic
    Posts
    36
    I tryed something like that, but it doesn't work. I think that I'm going in the wrong way.
    Code:
    const char wierdChara[2] = "|";          
    char *token;
         while(!feof(txt)){       
            token = strtok(txt, wierdChara);
            while(token != NULL){
                fgets(menaC, 40, txt);
                printf("\n%s", menaC);
                token = strtok(NULL, wierdChara);
            }
        }
    strtok don't working with file, i have warning on it

  9. #9
    Registered User
    Join Date
    Jun 2014
    Posts
    79
    My grandmother was used to saying that "the one who doesn't say no is shouting a silent yes" (I poorly translated it from the Italian original, I bet there is an equivalent English saying that states the very same thing in a better way). So here is what I put together:

    Code:
    /*
    IMPORTANT NOTICE: PROVIDE THAT YOUR DATA FILE ENDS WITH A
    '\n' CHARACTER, OR THE LAST LINE'S NOT GOING TO BE READ!!!
    */
    
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    #define kDimBuffer      1024
    #define kItemsPerLine   5
    
    
    int main() {
        FILE *dataFile = NULL;
        char *line = NULL;
        char item[256];
        char *pLine, *pItem;
        int i, j, lineLength;
    
        /* opens the data file */
        if( (dataFile=fopen("data.txt","r")) == NULL )
            { printf( "\nFile not available.\n" ); goto cleanup_and_quit; }
    
        /* allocates memory for the buffer */
        if( (line=malloc(kDimBuffer)) == NULL )
            { printf( "\nInsufficient memory.\n" ); goto cleanup_and_quit; }
    
        /* reads one line at the time */
        for( i=0; fgets(line,kDimBuffer,dataFile)!=NULL; ++i ) {
            if( i>1 ) { /* allows skipping the first two lines */
                /* checks the length of the line read */
                lineLength = strlen( line );
    
                if( line[lineLength-1] == '\n' ) {
                    /* gets rid of the nasty '\n' character */
                    line[--lineLength] = '\0';
                }
                else {
                    /* if the '\n' character is empty, the the buffer
                       is too small, so we have to abort the program */
                    printf( "\nYour buffer is too small.\n" );
                    goto cleanup_and_quit;
                }
    
                /* provides an auxiliary pointer to line */
                pLine = line;
    
                /* reads the items from the line, one by one */
                for( j=0; j<kItemsPerLine; ++j ) {
                    /* copies one character at a time into "item" */
                    for( pItem=item; *pLine!='|'&&*pLine!='\0'; ++pItem, ++pLine )
                        *pItem = *pLine;
                    *pItem = '\0'; /* terminates the string */
    
                    /* do here whatever you like with the extracted item
                       as an example, we just print it to the console */
                    printf( "Line %d, item %d: %s\n", i-1, j+1, item );
                    /* adds a new line, just for readability */
                    if( j == 4 ) printf( "\n" );
    
                    /* skips the '|' or the '\n' character
                       (at the end of the loop skips the '\0'
                       as well, but it doesn't make any harm)*/
                    ++pLine;
                }
    
                /* stops, waiting for the user key-press */
                system( "PAUSE" );
                system( "CLS" );
            }
        }
    
        printf( "\nEnd of file. We did it!\n\n" );
    
        cleanup_and_quit:
        system( "PAUSE" );
        system( "CLS" );
        if( line != NULL )
            free( line );
        if( dataFile != NULL )
            fclose( dataFile );
        return 0;
    }
    Is it correct or did I miss the point?

  10. #10
    Registered User
    Join Date
    Jun 2005
    Posts
    6,815
    Quote Originally Posted by aldo_baldo View Post
    My grandmother was used to saying that "the one who doesn't say no is shouting a silent yes"
    Moderators aren't present 24/7, so equating "no answer from moderator" to "moderator has agreed with what I'm doing" is specious.

    My view - although I'm not a moderator - is that you are attempting to spoon feed and going against the site homework policy.

    The thing you haven't realised is that spoonfeeding might boost your ego ("See guys, I can do this!") but does a disservice to the person you're helping - or people who have to work with that person - since they often don't actually learn a damned thing.
    Last edited by grumpy; 12-28-2014 at 06:47 AM.
    Right 98% of the time, and don't care about the other 3%.

    If I seem grumpy or unhelpful in reply to you, or tell you you need to demonstrate more effort before you can expect help, it is likely you deserve it. Suck it up, Buttercup, and read this, this, and this before posting again.

  11. #11
    Registered User
    Join Date
    Jun 2014
    Posts
    79
    My question ("Is it correct or did I miss the point?") regards the code, not my grandmother saying. I'm not sure I solved the puzzle correctly, so I was -- and I am -- asking for an advice. I would like to see a solution employing wchar's too, as I never used them (in my opinion, sample code IS a useful learning tool, not just a source for copy/paste; most reference material include sample code). I'm not doing any homework, as I'm a 50 years old hobbyist -- no one gives me any assignment as regard programming.

    No ego to boost, as I know very well that I can hardly be regarded as a "programmer" at all. Just a hobbyist, as I wrote.

  12. #12
    Registered User
    Join Date
    Dec 2014
    Location
    Czech Republic
    Posts
    36
    For now i have something like this:

    Code:
    #include <stdio.h>#include <stdlib.h>
    #include <string.h>
    
    
    int main(void)
    {
        FILE *mena;
        mena = fopen("mena.txt", "r");
    
    
        if(mena == NULL){
            printf("Error: soubor nebyl nalezen.");
            return 1;
        }
    
    
        char zeme[20], menaC[20], kod[10], radek[50];
        int mnozstvi;
        float kurz;
    
    
        for(int i = 0; fgets(radek, 50, mena) != NULL; ++i){    // there for line
            if(i > 1){
                printf("%s", radek); // testing
            }
        }
        puts("\n");
    
    
        fclose(mena);
    
    
        puts("");
        return 0;
    }
    Output: Ignoring most information from File.-fd-png

    between if(i > 1) i want saving to string names without '|'.
    Something like this:
    Code:
    fscanf(radek, "%s %s %d %s %f, zeme, menaC, mnozstvi, kod, kurz);
    //and only print
    printf("%d %s = %f", mnozstvi, kod, kurz);
    Or, i am thinking about to ignore whole starting letters and start saving from first number.
    Last edited by Siggi; 12-28-2014 at 09:00 AM.

  13. #13
    Registered User
    Join Date
    Jun 2014
    Posts
    79
    Mmm... I think that in order to use fscanf() you should first substitute each '|' with a space. I fear that every state name made by two or more words (i.e. "New Zealand") could mess things up, too. Moreover, your exchange values are expressed in the form "0,60" (the decimal point being a comma) which could be ok or not, depending on the settings of your system (functions declared in locale.h could help).

    A different approach could be getting rid of every space (maybe substituting it with some other character, like the underscore '_'?), then substituting each '|' with a space. Personally, I don't like it.

    Another solution could be finding the location of each '|' character with strchr(), declared in string.h.

    As an example, let's take into account this line of data:

    Code:
    char data[] = "New Zealand|NZD|1|euro|0,60\n"
    One could store the beginning of each partial string of data like this:

    Code:
    #define kDataColumns        5
    
    char data[] = "New Zealand|NZD|1|euro|0,60\n";
    char *dataPtrs[kDataColumns];
    int i;
    
    for( dataPtrs[0]=data, i=1; i<kDataColumns; ++i )
        dataPtrs[i] = strchr(dataPtrs[i-1],'|')+1;
    Then, each '|' character and the '\n' at the very end of the string could be changed with '\0' terminators, to make each substring "independent".

    Code:
    for( i=0; data[i]!='\0'; ++i )
        if( data[i] == '|' || data[i] == '\n' )
            data[i] = '\0';
    Now the pointers in the vector dataPtrs[] can be used directly as C strings or converted into long or double values via atol() or atof() (see stdlib.h).
    Last edited by aldo_baldo; 12-28-2014 at 01:39 PM.

  14. #14
    Registered User
    Join Date
    Jun 2005
    Posts
    6,815
    Quote Originally Posted by aldo_baldo View Post
    My question ("Is it correct or did I miss the point?") regards the code, not my grandmother saying.
    The question was applicable to both. When you choose to breach the site's homework policy - which exists for good reasons - I choose not to review your code. No matter how good or bad it might be.

    The thing you haven't grasped is that spoonfeeding answers is a lazy approach. Helping people to learn without spoonfeeding actually takes more effort. You might want to ponder the question of why experienced people choose the approach that involves more effort.
    Right 98% of the time, and don't care about the other 3%.

    If I seem grumpy or unhelpful in reply to you, or tell you you need to demonstrate more effort before you can expect help, it is likely you deserve it. Suck it up, Buttercup, and read this, this, and this before posting again.

  15. #15
    Registered User
    Join Date
    Jun 2014
    Posts
    79
    As you like, Grumpy. No problems on my side.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Ignoring the stdio.h file in a c file
    By Raj 89 in forum C Programming
    Replies: 4
    Last Post: 11-28-2012, 11:08 AM
  2. removing/ignoring carrage returns from a file
    By katipo in forum C Programming
    Replies: 3
    Last Post: 12-01-2008, 03:55 PM
  3. Ignoring line in C++ when reading from file
    By falzone in forum C++ Programming
    Replies: 7
    Last Post: 11-16-2007, 12:08 AM
  4. File information in C
    By jakewendt in forum C Programming
    Replies: 2
    Last Post: 10-11-2002, 04:12 PM
  5. Ignoring a word from a .txt file
    By TrojanGekko in forum C++ Programming
    Replies: 1
    Last Post: 01-21-2002, 05:14 PM