Click here to Skip to main content
15,920,110 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Implementation detail is as follows:

1. Set the cursor in (5*i) position [i = 1 to n]
2. Read next 4 bytes
3. Set the cursor in (4*i) position [i = 1 to n]
4. Write the 4 bytes get from step 2.


C++
    FILE* hFile = nullptr;
hFile = fopen("D:\\FifthByte.txt", "r+");
if (hFile)
{
    int readPos = 5;
    int writePos = 4;
    //find the file size
    fseek(hFile, 0, SEEK_END);
    int size = ftell(hFile);
    char szText[4];
    //set the cursor in fifth position
    fseek(hFile, readPos, SEEK_SET);
    while (size > readPos + 4)
    {
        fread(&szText, sizeof(char), 4, hFile); //read next four bytes
        readPos += 5;    //update the read position for next read
        fseek(hFile, writePos, SEEK_SET);  //Set the cursor for write
        fputs(szText, hFile);  //write the four bytes
        writePos += 4;    //update the write position for next write
        fseek(hFile, readPos, SEEK_SET);
    }
    fclose(hFile);
}


But the above code not working.
Content of my "D:\\FifthByte.txt" file is 

1234512345123451234512345123451234512345

After execution the content becomes 

12341234ÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌ(ÌÌ(4Ì(34ÌÌÌÌÌÌÌÌ(


Can anybody tell what is the problem with above code?
Posted
Updated 25-Sep-15 21:42pm
v2

1 solution

fputs write a zero terminated string to the file, but szText is not zero terminated when filed with fread.

Use the debugger and follow variables.
 
Share this answer
 
Comments
Shubha Debnath 28-Sep-15 5:00am    
Thanks for your support. I append a null character at the end after fread() and it is working. Thanks again.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900