Accessing int at end of file

This is a discussion on Accessing int at end of file within the C Programming forums, part of the General Programming Boards category; Hi, I'm learning to use files in C and I was wondering how to access an integer at the end ...

  1. #1
    Registered User
    Join Date
    May 2012
    Location
    Madrid, Spain, Spain
    Posts
    8

    Accessing int at end of file

    Hi, I'm learning to use files in C and I was wondering how to access an integer at the end of a text file.
    The file has some strings before, and the last line should be:

    Output=6

    I'd like to make a function that stores that 6 in a variable and returns it.
    I've managed to store integers when the file is made just out of numbers, eg:
    Code:
    FILE *pf;
        int i;
        int input[]={25,1,2,5,4};
        int output;
        char pepe[20]="pepe";
        
        pf=fopen("test.txt","w"); 
        for(i=0;i<5;i++)
        fprintf(pf,"%d\n",input[i]);
        fclose(pf);
        
        pf=fopen("test.txt","r");
        while(fscanf(pf,"%d",&output)!=EOF)
           printf("Output: %d\n",output);
        fclose(pf);
    But not when there are strings throughout the file.
    Any help?
    thanks!

  2. #2
    - - - - - - - - oogabooga's Avatar
    Join Date
    Jan 2008
    Posts
    2,808
    If you can be absolutely certain that there will not be another line after the last line (not even an extra space) then something like this will work:
    Code:
        while (fgets(line, sizeof line, pf))
            ;
        // Now line will contain the last line.
        sscanf(line, " Output = %d", &n);
    The extra spaces around the word "Output" and the "=" allow there to be spaces (or not) in the string.

    If it's possible that there is an extra blank line at the end of the file, or if you just want to be more careful, then you'll have to do it more like this:
    Code:
    while (fgets(line, sizeof line, pf)) {
        if (!isBlank(line)) // you have to write isBlank()
            strcpy(last_line, line);
    }
    sscanf(last_line, " Output = %d", &n);
    The cost of software maintenance increases with the square of the programmer's creativity. - Robert D. Bliss

  3. #3
    Registered User
    Join Date
    May 2012
    Location
    Madrid, Spain, Spain
    Posts
    8
    I'm sorry but, being a novice, i don't quite understand your code there.
    I assume it looks for the last written line, copies it to another string and then uses sscanf to identify the integer
    Evenif I interpreted the behaviour correctly (which I doubt), I dont understand how the condition for your while works.

    Last, is the isBlank() function supposed to check if a string is blank?
    Thank you very much!

  4. #4
    Registered User whiteflags's Avatar
    Join Date
    Apr 2006
    Location
    United States
    Posts
    7,627
    I assume it looks for the last written line, copies it to another string and then uses sscanf to identify the integer
    Well it actually reads the whole file and skips over most of the content. By the time you reach the end of the file, the last line is still in last_line, and sscanf identifies the integer. If you needed the other content in the file you would have to use rewind(FILE*) first.

    Last, is the isBlank() function supposed to check if a string is blank?
    If you had a file that ended with a blank line, there would actually be a string like "\n".

    I dont understand how the condition for your while works.
    Code:
      while (fgets(line, sizeof line, pf) != NULL)
    My own edits aside, it's the way to read a text file line by line in C. fgets is called and it returns a string, or NULL on failure, that will be used to control the loop. When fgets returns NULL, it should break.

    Hi, I'm learning to use files in C and I was wondering how to access an integer at the end of a text file.
    Read the text file in order first and then the integer at the end will eventually come. Use the other content first. That's my take on it anyway. Skipping around a binary file is easier than this. (shrug)

  5. #5
    Registered User
    Join Date
    May 2012
    Location
    Madrid, Spain, Spain
    Posts
    8
    Thank you both, I now understand how the function works, but I'm still fighting with the isBlank() condition:
    Quote Originally Posted by whiteflags View Post
    If you had a file that ended with a blank line, there would actually be a string like "\n".
    Then,
    Code:
    if(line!="\n")
    should do the trick, right?
    I've tried it but I don't get the desired result

  6. #6
    Frequently Quite Prolix dwks's Avatar
    Join Date
    Apr 2005
    Location
    Canada
    Posts
    8,046
    When comparing strings in C, you can't use == or != directly. You have to call the function strcmp() for "string compare".

    This is because "\n" is a string constant located somewhere in memory, and line can be treated as a pointer to the first element of the array; so the == or != syntax is really checking whether the pointers are actually the same or not. This is clearly not what you want, since "\n" will be put by the compiler at some special place in memory, and your line buffer will be elsewhere; hence the pointer comparison will always indicate that line != "\n".
    dwk

    Seek and ye shall find. quaere et invenies.

    "Simplicity does not precede complexity, but follows it." -- Alan Perlis
    "Testing can only prove the presence of bugs, not their absence." -- Edsger Dijkstra
    "The only real mistake is the one from which we learn nothing." -- John Powell


    Other boards: DaniWeb, TPS
    Unofficial Wiki FAQ: cpwiki.sf.net

    My website: http://dwks.theprogrammingsite.com/
    Projects: codeform, xuni, atlantis, nort, etc.

  7. #7
    Registered User
    Join Date
    May 2012
    Location
    Madrid, Spain, Spain
    Posts
    8
    Seriously, I'm gonna end up in a madhouse!
    This is my function:
    Code:
    int get_data(FILE *pf){
        int data=0;
        char line[CHAR];
        char last_line[CHAR];
        char empty_line[CHAR]="\n";
        while(fgets(line,sizeof line,pf)){
            if(strcmp(line,empty_line)!=0)
                strcpy(last_line,line);                         
        }
        sscanf(last_line,"Total sencillos = %d",&data);
        return data;

    where CHAR represents 140.
    This is my function call:
    Code:
    
        int total_sencillos=0;
        pf=fopen("BONOSSENCILLOS.txt","a");
        total_sencillos=get_data(pf);
        total_sencillos++;
        fprintf(pf,"Total sencillos=%d\n",total_sencillos);
        return pf;
    }
    And it keeps reading 0 and writing 1, time after time
    I'm a few hours away from smashing my computer

  8. #8
    Registered User
    Join Date
    May 2010
    Posts
    2,690
    What exactly is contained in the last line? When you use the scanf() family with a constant that constant must be retrieved exactly or the retrieval will fail. For example you are writing "Total sencillos=%d\" to your file, notice no spaces. But you try to retrieve "Total sencillos = %d", notice the spaces.

    See the following quote form the above link.

    The format string consists of a sequence of directives which describe how to process the sequence of input characters. If processing of a directive fails, no further input is read, and scanf() returns. A "failure" can be either of the following: input failure, meaning that input characters were unavailable, or matching failure, meaning that the input was inappropriate (see below).

    A directive is one of the following:



    A sequence of white-space characters (space, tab, newline, etc.; see isspace(3)). This directive matches any amount of white space, including none, in the input.

    • An ordinary character (i.e., one other than white space or '%'). This character must exactly match the next character of input.

    Jim

  9. #9
    Registered User
    Join Date
    May 2012
    Location
    Madrid, Spain, Spain
    Posts
    8
    Quote Originally Posted by jimblumberg View Post
    You are writing "Total sencillos=%d\" to your file, notice no spaces. But you try to retrieve "Total sencillos = %d", notice the spaces.
    From your quote:
    A sequence of white-spae characters. This directive matches any amount of white space, including none, in the input.
    I have tried changing everything to "Total sencillos = %d" and also to "Total sencillos=%d", with no luck
    Last edited by GCWilkins; 05-21-2012 at 09:12 AM.

  10. #10
    Registered User
    Join Date
    May 2012
    Location
    Arizona, USA
    Posts
    383
    Quote Originally Posted by GCWilkins View Post
    Code:
        int total_sencillos=0;
        pf=fopen("BONOSSENCILLOS.txt","a");
        total_sencillos=get_data(pf);
        total_sencillos++;
        fprintf(pf,"Total sencillos=%d\n",total_sencillos);
        return pf;
    }
    You're not opening the file for reading. The "a" mode string tells fopen to open the file for appending (writing at the end of the file). Since you want to read from the file too, you need to add a "+" after the mode string, so it becomes "a+".

  11. #11
    Registered User
    Join Date
    May 2010
    Posts
    2,690
    I believe that the quote about the white-space characters is only valid for the beginning of the string before any other character is encountered.

    I don't recommend trying to use a "constant" in your scanf(), in my opinion you would be better off using strtok() with the '=' as the token. Then use atoi() to convert that string to a number. The other option if there is a space separating the '=' from your number is to retrieve the string into a temporary string and then retrieve your number.
    Example for a value of "Total sencillos = 140" in your file:
    Code:
    char trash[100];
    int valueWanted;
    sscanf(last_line,"%s%s%s%d",trash,trash,trash, &valueWanted);
    Jim

  12. #12
    Registered User
    Join Date
    May 2012
    Location
    Madrid, Spain, Spain
    Posts
    8

    Thumbs up Solved

    Big thanks to all of you!
    I finally solved my problem by changing the way data is written to the file:
    I made sure it always had three digits and then used fseek() to point to SEEK_END - 3. fscanf did the rest for me.
    It's been pretty frustrating, but I learned quite a lot from your replies.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Accessing a file with threads
    By clancyPC in forum C Programming
    Replies: 3
    Last Post: 09-14-2007, 10:01 AM
  2. accessing Delphi written file
    By Sha in forum C Programming
    Replies: 3
    Last Post: 12-12-2006, 11:50 PM
  3. accessing file properties
    By subodh_dg in forum Windows Programming
    Replies: 2
    Last Post: 12-25-2005, 11:23 PM
  4. accessing a variable from another C file
    By cblix in forum C Programming
    Replies: 3
    Last Post: 12-05-2005, 05:16 AM
  5. accessing bytes of a file
    By neandrake in forum C++ Programming
    Replies: 2
    Last Post: 03-05-2002, 07:41 PM

Tags for this Thread


1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21