Reading a potentially incomplete C ++ file

I am writing a program to reformat a DNS log file for insertion into a database. There is a possibility that the line that is currently being written to the log file is incomplete. If so, I would like to abandon it.

I began to believe that the function eofmight be suitable for my application, however I noticed that many programmers discourage the use of the function eof. I also noticed that the function feofseems very similar.

Any suggestions / explanations that you guys could report on the side effects of these functions would be most appreciated, as would any suggestions for more suitable methods!

Edit: I am currently using a function istream::peekto skip the last line, whether it is complete or not. Although this is acceptable, a solution that determines whether the last line is completed would be preferable.

The specific comparison I'm using is: logFile.peek() != EOF

+4
source share
2 answers

I would like to use

int fseek ( FILE * stream, long int offset, int origin );

from SEEK_END

and then

long int ftell ( FILE * stream );

to determine the number of bytes in the file and, therefore, where it ends. I found this more reliable in detecting the end of the file (in bytes).

EOR ( /) (, CRLF) ? (3 CRLF ^ Z... ). ,

fseek (stream, -2,SEEK_END);
fread (2 bytes... etc

, ( ), , ... ( )

+2

, , .

- ++ - . FILE *, fopen() fread() - , , , , .

POSIX open() read()/pread() C-. fstat(), , . fstat() st_size struct stat.

:

int logFileFD = open( "/some/file/name.log", O_RDONLY );

- ( ):

size_t lastSize = 0;
while ( !done )
{
    struct stat statBuf;
    fstat( logFileFD, &statBuf );
    if ( statBuf.st_size == lastSize )
    {
        sleep( 1 ); // or however long you want
        continue;   // go to next loop iteration
    }
    // process new data - might need to keep some of the old data
    // around to handle lines that cross boundaries
    processNewContents( logFileFD, lastSize, statBuf.st_size );
}

processNewContents() :

void processNewContents( int fd, size_t start, size_t end )
{
    static char oldData[ BUFSIZE ];
    static char newData[ BUFSIZE ];

    // assumes amount of data will fit in newData...
    ssize_t bytesRead = pread( fd, newData, start, end - start );

    // process the data that was read read here

    return;
}

, close(), open() , , , "" , . , - - -, ls , , . , , , 10-15 , 30 , - , , , .

inode struct stat, .

, POSIX, open(), fstat() pread() , Windows , . Windows lseek(), read() pread().

0

Source: https://habr.com/ru/post/1623318/


All Articles