Link to home
Start Free TrialLog in
Avatar of Varadha2k
Varadha2k

asked on

Code Optimization

Hi,

I am trying to insert a LineFeed at the end of every 100th character in my file.
I am using the following code for this.
It takes a long time if the file has some 100,000 characters. So can u suggest me a idea to do it faster.


Code:

char *file;
char *file1;

unsigned long offset = 0;
char   buf[102] = {0};
HANDLE hFile, hFile1 ;
DWORD  dnbytes = 0;
DWORD  dwact = 0;
DWORD  lowsize = 0;
DWORD  hisize = 0;
int    nStartIndex = 0;


if ((hFile = CreateFile(file,
      GENERIC_READ,
      0,
      NULL,
      OPEN_EXISTING,
      FILE_FLAG_RANDOM_ACCESS,
      NULL) )
== INVALID_HANDLE_VALUE)
return 1;

lowsize = GetFileSize(hFile, &hisize);
if (lowsize == 0xffffffff)
{
CloseHandle(hFile);
return FAILURE;
}

if ((hFile1 = CreateFile(file1,
       GENERIC_WRITE,
       0,
       NULL,
       OPEN_EXISTING,
       FILE_FLAG_RANDOM_ACCESS,
       NULL) )
== INVALID_HANDLE_VALUE)
{
CloseHandle(hFile);
return FAILURE;      
}


while (1)
{
dnbytes = 100;        

if (!ReadFile(hFile,buf,dnbytes,&dwact,0))
{
    CloseHandle(hFile);
    CloseHandle(hFile1);
    return SUCCESS;
}

// insert 0x0d at the end
if (dnbytes != dwact)
{
    dnbytes = dwact;
    if (dwact != 0)
 buf[dwact]=0x0d;
    CloseHandle(hFile);
    CloseHandle(hFile1);
    return SUCCESS;
}
else
{
    buf[dnbytes]=0x0d;
}

dnbytes++;

if (!WriteFile(hFile1, &buf[nStartIndex], dnbytes, &dwact, NULL))
{
    CloseHandle(hFile);  
    CloseHandle(hFile1);  
    return FAILURE;  
}

if (dnbytes != dwact)
{
    CloseHandle(hFile);  
    CloseHandle(hFile1);  
    return FAILURE;  
}
Sleep(1);      
}  
return 0;

Thanks in Advance,
Varadha
ASKER CERTIFIED SOLUTION
Avatar of stsanz
stsanz

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of drnick
drnick

also, you could speed a little up when reading and writing larger blocks.
make your buffer n*100+n bytes large,
read n*100 bytes,
use memmove or RtlMoveMemory to move the buffer content like

RtlMoveMemory(&buf[n*100-1], &buf[(n-1)*100], 100)
RtlMoveMemory(&bu[(n-1)*100-2], & buf[(n-2)*100, 100)
maybe in a loop, regarding how may bytes actually read
and then write the block again