Search code examples
clinuxunixasciiposix

Creating a random character in C


I am analyzing a function written by my teacher. It creates a file and fills it with "random content". As description says:

Content of the file is 10% of random [A-Z] chars at random positions, the rest is filled with zeros (not "0", ascii code zero).

This is the function:

void make_file(char *name, ssize_t size, mode_t perms, int percent){
    FILE* s1;
    int i;
    umask(~perms&0777);
    if((s1=fopen(name,"w+"))==NULL)ERR("fopen");
    for(i=0;i<(size*percent)/100;i++){
            if(fseek(s1,rand()%size,SEEK_SET)) ERR("fseek");
            fprintf(s1,"%c",'A'+(i%('Z'-'A'+1)));
    }
    if(fclose(s1))ERR("fclose");
}

What I don't understand is - when are the ascii zeros are being added to the file?

As I understand, the for-loop sets a random file position indicator every time, and then generates a character. I thought that, maybe it's the fseek() function that adds ascii zeros, but when I tried to call it once, with a constant size 5 (doesn't matter what is the constant size number), it just created an empty file, without any ascii zeros.

Edit: Appreciate your answers about fseek() and ascii zeros. I'm sorry about adding this as an edit: My another question about this code is - how is this part of code: 'A'+(i%('Z'-'A'+1)) creates a random character?


Solution

  • They aren't. When fseek() is used to skip portions and then write, the file has "holes" in it, which get filled with zeroes by the OS.