Reverse File Read
#8

I came up with something way simpler, I guess.
Noticed that you can write to any position in a file and it will automatically adjust its size (fills with spaces).

It now handles each line seperately, but directly writes them to the correct offset.

PHP код:
File_LReverse(const fnamein[], const fnameout[])
{
    new 
File:FIn = fopen(fnamein, io_read);
    if(!
FIn) return 0;
    new 
File:FOut = fopen(fnameout, io_write);
    if(!
FOut)
    {
        
fclose(FIn);
        return 
0;
    }
    new 
c, totalchars, buf[MAX_LINE_LENGTH], flen, llen, bool:nline;
    while((
c = fgetchar(FIn, 0, true)) > 0) // Get file size and check if last line has a new line character
    
{
        
flen ++;
        if(
c == '\n') nline = false;
        else 
nline = true;
    }
    if(
nline) flen += 2; // Account for the missing new line at the very end of the file. This must be known before writing, otherwise the offsets of all other lines change!
    
fseek(FIn); // Reset pointer
    
while((llen = fread(FIn, buf)))
    {
        
totalchars += llen; // Keep track of how many characters were already read in total
        
if(nline && totalchars == flen - 2 && llen < MAX_LINE_LENGTH-2) // If there was no new line at the very end and this is the last line, add "\r\n"
        
{
            
strcat(buf, "\r\n");
            
totalchars += 2;
        }
        
fseek(FOut, flen - totalchars, seek_start); // Navigate to the correct offset in the new file (end - total characters read)
        
fwrite(FOut, buf);
    }
    
fclose(FOut);
    
fclose(FIn);
    return 
1;
} 
Should be faster and also fix the random characters
Reply


Messages In This Thread
Reverse File Read - by Novacaine - 04.06.2017, 12:52
Re: Reverse File Read - by NaS - 04.06.2017, 21:39
Re: Reverse File Read - by Novacaine - 04.06.2017, 22:08
Re: Reverse File Read - by NaS - 04.06.2017, 22:19
Re: Reverse File Read - by Novacaine - 04.06.2017, 22:36
Re: Reverse File Read - by NaS - 04.06.2017, 23:29
Re: Reverse File Read - by Novacaine - 05.06.2017, 00:21
Re: Reverse File Read - by NaS - 05.06.2017, 08:56
Re: Reverse File Read - by Gammix - 05.06.2017, 09:05
Re: Reverse File Read - by Novacaine - 05.06.2017, 15:05

Forum Jump:


Users browsing this thread: 1 Guest(s)