使用单个文件指针从文件中删除多个第五个字节时出现问题 [英] Problem while deleting multiple of fifth byte from a file with a single file pointer

查看:86
本文介绍了使用单个文件指针从文件中删除多个第五个字节时出现问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

实现细节如下:

1.将光标置于(5 * i)位置[i = 1到n]
2。读取下一个4个字节
3.将光标置于(4 * i)位置[i = 1到n]
4.写入步骤2中的4个字节。

< br $>


 FILE * hFile =  nullptr ; 
hFile = fopen( D:\\FifthByte.txt r +);
if (hFile)
{
int readPos = 5 ;
int writePos = 4 ;
// 查找文件大小
fseek(hFile, 0 ,SEEK_END);
int size = ftell(hFile);
char szText [ 4 ];
// 将光标设置在第五位
fseek(hFile,readPos, SEEK_SET);
while (size> readPos + 4
{
fread(& szText, sizeof char ), 4 ,hFile); // 读取下四个字节
readPos + = 5 ; // 更新下次读取的读取位置
fseek(hFile,writePos,SEEK_SET); // 设置写入的光标
fputs(szText,hFile); // 写入四个字节
writePos + = 4 ; // 更新下一次写入的写入位置
fseek(hFile,readPos,SEEK_SET);
}
fclose(hFile);
}





但上面的代码无效。 
我的D:\\FifthByte.txt文件的内容是

1234512345123451234512345123451234512345

执行后内容变为

12341234大〜((((((((((((((((((((((((((((

fputs 将一个以零结尾的字符串写入文件,但 szText 在归档时不会终止 fread



使用调试器并关注变量。


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.



    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?

解决方案

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.


这篇关于使用单个文件指针从文件中删除多个第五个字节时出现问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆