Search code examples
cfwriteeoffread

Read, encrypting and writing a block of bytes


  • read 16 bytes from a file;
  • encrypt this 16 bytes;
  • write encrypted bytes to another file;
  • do the above things again until end of file;

If the last call is < 16 bytes i fill the buffer with 0.
Is this a correct way to do it?

FILE *fp = fopen("name", "r+");
FILE *fpout = fopen("name", "w+");
char plain_text[16];
fseek(fp, 0, SEEK_SET);

while(!feof(fp)){
  memset(plain_text, 0, sizeof(plain_text);
  read_bytes = fread(plain_text, 1, 16, fp);
  if(read_bytes < 16){
    i = read__bytes;
    read_bytes += 1;
    for(i, i<16, i++) plain_text[read_bytes] = 0;
  }
  encrypt-this-part-of-file
  fwrite(encBuffer, 1, 16, fpout);
}

Solution

  • no, this would be correct...

    if(read_bytes < 16)
    {
        for(i = read_bytes; i<16; i++)
        {
            plain_text[i] = 0;
        }
    }
    

    ...if you'd actually needed it.

    But you don't need to zero the remaining part of the array as you have already cleared it with...

    memset(plain_text, 0, sizeof(plain_text));
    

    ...that you're calling before each invokation of fread.