0

I need to realize this method (https://en.wikipedia.org/wiki/Padding_%28cryptography%29#PKCS7) using C, which don't have convenient function to do that.

I have added this way

int main()
{
    FILE *file=fopen("1.xlsx", "a"); 

   file_add(16,file);
   fclose(file);
}
void file_add(int SizeOfBlock, FILE *file )
{
    fseek(file, 0, SEEK_END);
    int size = ftell(file); // file size in bytes
    fseek(file, 0, SEEK_SET);

    int diff = size%SizeOfBlock;

    char arr[16] = "0000000000000000"; //16 zeroes
    fwrite(arr, SizeOfBlock-diff, 1 , file); // here I added to end of file missing 0 to make size of file  be dividing to SizeOfBlock

}


void file_remove (int SizeOfBlock, FILE *file)
{
  // by this function I need to delete these zeroes
  // max amount of zeroes is limited by SizeOfBlock
}

How can I do that? SizeOfBlock can be only 8 or 16

Rocketq
  • 5,423
  • 23
  • 75
  • 126
  • @Rocketq He means that your code is adding the printable character `0` (zero, ascii value 48) to the end of the file, not the actual `NUL` character. – Joachim Isaksson Dec 11 '13 at 09:11
  • Do you want to write 0 of digit character as padding? – BLUEPIXY Dec 11 '13 at 09:12
  • @BLUEPIXY I guess yes, and why not? Because isn't easy to delete these zeroes after all? I described here why I need such code http://stackoverflow.com/questions/20504653/how-to-properly-work-with-file-upon-encoding-and-decoding-it – Rocketq Dec 11 '13 at 09:13
  • How do you distinguish the character of as the contents of the file in that case(to delete)? – BLUEPIXY Dec 11 '13 at 09:15
  • 1
    @Rocketq Constant (zero) padding is only useful if you also store the original length of the file. Consider the file contents `00` padded to `00000000`, how many zeroes should you remove at the end of the file when removing padding? – Joachim Isaksson Dec 11 '13 at 09:16
  • 1
    I just predicted it, that file won't be with zeroes in the end, anyway it is not problem, how can I remove? I always can modify code and realize other padding – Rocketq Dec 11 '13 at 09:16

1 Answers1

1

To truncate a file you can use the following function:

#include <unistd.h>
int ftruncate(int fildes, off_t length);
int truncate(const char *path, off_t length);

Since ftruncate uses a filedescriptor, you have to get that descriptor from the FILE structure using fileno.

ftruncate(fileno(file), length);

If the new lenght, you specified, is longer than the current file, the file will grow, which may be a bit missleading, cosnidering the name of the function. So it actually can be also used to make a file larger, padding it with \0.

Devolus
  • 21,661
  • 13
  • 66
  • 113