【问题标题】:cannot write binary data in a file using c无法使用c在文件中写入二进制数据
【发布时间】:2013-06-23 07:14:23
【问题描述】:

我在 windows vista os 中使用 vs2010 问题是我想读取和 exe 文件加密并存储它但是当我写回数据时没有插入我的意思是文件已创建但没有错误和文件是空的,我已经做了一千次了,它可以在 eclipse 上运行,但不能在 vs2010 上运行,我需要将它移植到 gui 中,任何人都可以将我重定向到我错的地方

FILE *pFile, *file;
size_t result;

pFile = fopen(fName, "r+b");
if (pFile==NULL) {MessageBox(NULL, L"Could not open file", L"Information", MB_ICONERROR); return FALSE;}

fseek(pFile, 0 ,SEEK_END);
sData->fSize = ftell(pFile);
rewind(pFile);

sData->fbuffer = (unsigned char *) malloc(sizeof(char) * sData->fSize);
if (sData->fbuffer == NULL) {MessageBox(NULL, L"Memory error", L"Information", MB_ICONERROR); fclose(pFile); return FALSE;}

file = fopen("out.txt", "w+b");
while ((result = fread(sData->fbuffer, 1, sData->fSize, file)) > 0) {
    if (!(fwrite(sData->fbuffer, 1, result, file))) {
        MessageBox(NULL, L"Write error", L"Information", MB_ICONERROR);
    }
    fclose(file);
}
fclose(file);

//result = fread(sData->fbuffer, 1, sData->fSize, pFile);
//if (result != sData->fSize) {MessageBox(NULL, L"Read error", L"Information", MB_ICONERROR); fclose(pFile); return FALSE;}

fclose (pFile);

return TRUE;

编辑

真的很抱歉,问题出在文件的位置,它是 unicode 格式,因为 fopen 接受 ascii 并且该位置只显示 C 我必须将其转换以获得正确的结果,谢谢

【问题讨论】:

    标签: c++ c visual-studio-2010 msdn


    【解决方案1】:

    您可能希望在fread() 中使用pFile 而不是file

    //----------------------------------------------------  pFile not file
    while ((result = fread(sData->fbuffer, 1, sData->fSize, pFile)) > 0) {
        if (!(fwrite(sData->fbuffer, 1, result, file))) {
            MessageBox(NULL, L"Write error", L"Information", MB_ICONERROR);
        }
        fclose(file);
    }
    

    【讨论】:

    • @KeshavNair,是的 exe 文件已打开并分配在 file 而不是 pFile
    • 抱歉我改了还是不行
    【解决方案2】:

    我认为您打开读取的文件不是 Ascii,因此您假设基于 char 大小计算文件大小是错误的。 如果您以字节为单位计算正确的文件大小并读取和写入这么多字节,那么您应该没问题。

    【讨论】:

    • 这是我在 eclipse 中测试过的 Ascii
    【解决方案3】:

    您正在读取和写入同一文件。

    while ((result = fread(sData->fbuffer, 1, sData->fSize, file)) > 0) {

    if (!(fwrite(sData->fbuffer, 1, result, file))) {

    由于您刚刚打开此文件,它什么也没有读取,因此也没有写入任何内容。

    来自手册页:

    w+ or wb+ or w+b
    Truncate to zero length or create file for update.
    

    【讨论】:

    • 在切换位时如何做同样的事情?例如pbFile[I] ^= 0x55; 用于加密
    猜你喜欢
    • 2014-05-20
    • 2020-12-16
    • 2017-02-18
    • 1970-01-01
    • 1970-01-01
    • 2012-03-03
    • 1970-01-01
    • 2021-07-02
    相关资源
    最近更新 更多