Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

fread() isn't writing to the buffer

Tags:

c

windows

fread

#include <Windows.h> 
#include <stdio.h> 

int count = 0; 
FILE* pFile = 0; 
long Size = 0; 

void *memfrob(void * s, size_t n) 
{ 
    char *p = (char *) s; 

    while (n-- > 0) 
        *p++ ^= 42; 
    return s; 
} 

int main() 
{ 
    fopen_s(&pFile, "***", "r+"); 
    fseek(pFile, 0, SEEK_END); 
    Size = ftell(pFile); 
    char *buffer = (char*)malloc(Size); 
    memset(buffer, 0, Size); 
    fread(buffer, Size, 1, pFile); 
    fclose(pFile); 
    memfrob(buffer, Size); 
    fopen_s(&pFile, "***", "w+"); 
    fwrite(buffer, Size, 1, pFile); 
    fclose(pFile); 
}

Hi, fread isn't reading anything from file to buffer and I can't figure out why. Could someone give me a hint or a push in the right direction?

like image 568
Chuy Avatar asked Dec 08 '22 01:12

Chuy


2 Answers

You need to seek back to the beginning of the file before you fread.

like image 72
jcopenha Avatar answered Dec 27 '22 23:12

jcopenha


You did a fseek to the end of the file and didn't fseek back before you did the fread.

like image 45
Paul Tomblin Avatar answered Dec 28 '22 00:12

Paul Tomblin