banner



How to Read the Last Line of a File in C

  1. #1

    c_geek is offline

    Registered User


    Open a file and read it from the last line

    Hi All
    I am having a problem here. I have a file which saves the data as follows:

    Thu 01/24/2008 8:59:27.42 - entry, aa_1, SYS_ADMIN
    Thu 01/24/2008 9:01:45.02 - exit, aa_1, SYS_ADMIN
    Thu 01/24/2008 9:02:28.69 - entry, aa_1, SYS_ADMIN
    Thu 01/24/2008 9:02:45.21 - go out, aa_1, SYS_ADMIN

    I want to open this file and read concluding row(the latest logged line), too i dont want to read the whole line all i am interested in is the word "SYS_ADMIN" in the latest logged row. How tin can i achieve this in C Programming?...your help will highly exist appreciated. I am pretty novice in C programming so your help will highly exist regarded. Thanks in advance!


  2. #2

    foxman is offline

    Chinese p�t� foxman's Avatar


    There's some functions defined in the stdio.h and cord.h header who could help you solve your trouble. One way to practice and then is to:
    1. Open up the file (of class..) (fopen)
    2. Position it at the "end of the file - X" (fseek)
    3. Read 10 characters (fgets)
    4. Find the last occurrence of a space in the string you lot but read (strrchr). What yous are interested nigh will be at that position + 1.
    5. Eventually, close the file... (fclose)


  3. #3

    esbo is offline

    Fountain of cognition.


    I have a like trouble in that I wrote a program to process a text file containing variable number of records such as.

    Code:

    Record 1 outset. ... ... variable number of lines.. ...... ....... Record 1 finish  Tape 2 start. ... ... variable number of lines.. ...... ....... Tape ii end  Record iii start. ... ... variable number of lines.. ...... ....... Record iii end
    However at present I need to read the records in contrary order 3, 2,one etc....

    Probably would be easier just to write a plan to opposite the records I think, and keep the existing program every bit it is.
    I guess the original affiche could do that - read everything into an array and them write out a new file starting from the end of the array??
    It is a bit more complicated in my case as I would have to search back for "Tape 3 commencement", in the example in a higher place then write out each line untill i got to 'record three end' and then search back for 'Record two showtime' and repeat the process.
    Would probably be the easiest method for me overall I think.


  4. #iv

    Elysia is offline

    C++まいる!Cをこわせ!


    Problem is that you won't know at what position the concluding line is, then it's impossible to seek directly.
    Thus, there are two ways if you don't want to re-write the file, which I can come across.
    1. Read the file line-by-line until you lot find the last line.
    2. Seek to stop and read backwards until you discover a newline. From that bespeak onwards would be the last line (also take into mind that the concluding character in the file might be a newline or several newlines).

    Quote Originally Posted by Adak View Post

    io.h certainly IS included in some modern compilers. Information technology is no longer part of the standard for C, but it is however, included in the very latest Pelles C versions.

    Quote Originally Posted by Salem View Post

    Yous mean it's included equally a crutch to help ancient programmers limp forth without them having to relearn too much.

    Exterior of your DOS world, your header file is meaningless.


  5. #5

    c_geek is offline

    Registered User


    How tin can i read characters (with fgetc) backwords? I open a file, seek it to the end of the file (with fseek(fp,0,SEEK_END)) and and then start reading backwords untill i meet ','.?

    Is at that place a mode to do it?

    Thanks in advance


  6. #6

    nacho4d is offline

    Registered User


    an alternative answer perchance

    takes you to the stop of file (as you already should know.)
    you can use fgetc in a loop and increment the value of 0L to 1L 2L .... etc. and in every iteration you compare if it is "," . or if you already know the length of "SYS_ADMIN" yous just practice
    fseek (fp, sizeof("SYS_ADMIN"), 2).

    in one case y'all do that you lot can exercise as always with fgetc ...

    by the way you should expect at The GNU library reference manual. I am certain you will observe something better.


  7. #7

    whiteflags is offline

    Lurking whiteflags's Avatar


    > fseek (fp, sizeof("SYS_ADMIN"), two).
    Unfortunately the sizeof "SYS_ADMIN" and the length of "SYS_ADMIN" are different things entirely. The size of the cord is equivalent to sizeof (char * ).

    If the format is simple plenty I don't come across a problem with reading the whole file line-by-line and afterward simply searching the last line for the appropriate content. It'due south certainly no slower than the proposed alternatives. In one case you lot find the word in the expanse you're interested in you can re-create it or do whatsoever you wanted with it.

    It does accept the do good of solving the problem without resorting to "reading backwards," which may mess up future processing.

    Final edited past whiteflags; 01-25-2008 at 02:29 PM.


  8. #8

    c_geek is offline

    Registered User


    Quote Originally Posted by nacho4d View Post

    takes you to the end of file (as you already should know.)
    yous can use fgetc in a loop and increment the value of 0L to 1L 2L .... etc. and in every iteration you compare if it is "," . or if you already know the length of "SYS_ADMIN" you just practise
    fseek (fp, sizeof("SYS_ADMIN"), ii).

    in one case you do that y'all can do as always with fgetc ...

    by the manner yous should look at The GNU library reference manual. I am certain you lot will observe something amend.

    Thank you for your answer, few comments on information technology, i increment it past 0L,1L,2L etc, i am already at the cease of the file, past incrementing this, i volition be going in forward direction non the backward management, Is information technology right? Besides fgetc will requite me an integer back, will i have to compare information technology'due south value to the ascii value of ','(comma) or i tin simply use comma in the compare string?

    Cheers


  9. #9

    Salem is online now

    and the hat of int overfl Salem's Avatar


    > The size of the string is equivalent to sizeof (char * ).
    Are you sure?

    Seek to the terminate of the file, minus say 100 bytes.
    Call fgets() until cease of file is reached.
    The final outcome from fgets() will exist the last line of the file.


  10. #10

    foxman is offline

    Chinese p�t� foxman's Avatar


    Hither's a bit of code of what i had in head

    Code:

    #include <stdio.h> #include <string.h> #define LARGE_ENOUGH_VALUE 12l   // But not to big either...  int principal(void) {     FILE *file;     char buffer[LARGE_ENOUGH_VALUE];     char *ptr;      if ((file = fopen("test.txt", "rt")) != NULL)     {         if (fseek(file, -LARGE_ENOUGH_VALUE, SEEK_END) != 0)             printf("Error: fseek returned nonzero value\n");         else         {             if (fgets(buffer, LARGE_ENOUGH_VALUE, file) == NULL)                 printf("Error: fgets returned NULL\n");             else             {                 if ((ptr = strrchr(buffer, ' ')) == NULL)                     printf("Error: no space in the line read\n");                 else                 {                     // Hither you could think about removing the '\northward' if there is one                     printf("The terminal word is: &#37;s\n", ptr + i);                 }             }         }     }          return 0; }
    Anyhow. There's more systematic solution like the one Salem proposed (ie, checking if the line y'all only read is actually the final line of the file, which is something my lawmaking isn't doing) but if your log file accept a actually "standard structure", the solution i gave could too work. But it yet would be proficient to bank check if the line you read with fgets is really the last line of the file... and since this is not hard to implement, well, y'all know what you accept to exercise at present.
    Final edited past foxman; 01-25-2008 at 04:13 PM. Reason: Wrote "line" instead of "file"


  11. #eleven

    Elysia is offline

    C++まいる!Cをこわせ!


    Quote Originally Posted by citizen View Post

    > fseek (fp, sizeof("SYS_ADMIN"), 2).
    Unfortunately the sizeof "SYS_ADMIN" and the length of "SYS_ADMIN" are unlike things entirely. The size of the string is equivalent to sizeof (char * ).

    Visual Studio returns the length, in bytes, of the bodily string and not the size of the char* pointer itself.

    Code:

    size_t n = sizeof("This is a examination cord");
    Returns 22.

    Code:

    size_t n = sizeof(L"This is a examination string");
    Returns 44.

    Quote Originally Posted by Adak View Post

    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, simply information technology is still, included in the very latest Pelles C versions.

    Quote Originally Posted by Salem View Post

    You hateful it's included as a crutch to help ancient programmers limp along without them having to relearn besides much.

    Outside of your DOS world, your header file is meaningless.


  12. #12

    nacho4d is offline

    Registered User


    Quote Originally Posted by c_geek View Post

    Cheers for your answer, few comments on it, i increase it past 0L,1L,2L etc, i am already at the end of the file, past incrementing this, i will exist going in forward direction not the backward direction, Is information technology right? As well fgetc will give me an integer back, will i have to compare it'southward value to the ascii value of ','(comma) or i can just employ comma in the compare string?

    Thanks

    in fseek () the 2d argument is the offset. Wich means the distance between the current position and (in case the 3rd statement is 2)the terminate of file. or the distance between the current and the commencement of file (in case the 3rd argument is 1)
    the 2nd statement must exist a long that is why I put and "L" (ie : 0L, 1L, 2L)

    in other words. for going backwards from the terminate of file you should set up the 3rd argument 2.
    and increase the 2nd argument everytime you lot want to compare the character.

    Regarding the integer comparation. well sorry i mistaked, haha. i dont remember very goog merely i am sure there is a function to become the character (as a char type). maybe something like fgets() ??


  13. #13

    nacho4d is offline

    Registered User


    some other idea

    why dont use this?

    Code:

    [Function]  char * strrchr (const char *string, int c )  The role strrchr is similar strchr, except that information technology searches backwards from the cease  of the string string (instead of forward from the front).  For example,  strrchr ("hullo, world", �l�)  ⇒ "ld"
    in your file you have a lot of lines but I think you tin can accommodate that right? mayhap coping a entire line to a cord, and then you utilise the function above
    As I sayd before is a very good thought to take a expect to the GNU C manual reference. If you want to master functions and arrangement calls is a good start expert luck.


  14. #xiv

    Elysia is offline

    C++まいる!Cをこわせ!


    Quote Originally Posted by nacho4d View Post

    Only now seriously, we are supposed to use SEEK_SET, SEEK_END for a reason, instead of pure numbers. It makes the lawmaking more readable, so use them!

    Quote Originally Posted by Adak View Post

    io.h certainly IS included in some modern compilers. It is no longer function of the standard for C, just information technology is nevertheless, included in the very latest Pelles C versions.

    Quote Originally Posted by Salem View Post

    You mean it'due south included as a crutch to assist ancient programmers limp along without them having to relearn as well much.

    Outside of your DOS globe, your header file is meaningless.


  15. #xv

    Salem is online now

    and the hat of int overfl Salem's Avatar


    /me points out that random seeks on a text file are undefined to begin with.


How to Read the Last Line of a File in C

Source: https://cboard.cprogramming.com/c-programming/98250-open-file-read-last-line.html

0 Response to "How to Read the Last Line of a File in C"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel