Whizzil
Whizzil

Reputation: 1364

C: simultaneous reading from and writing to file

What i would like to do: Read bits from one file (input file), and write these (with some probability) inverted bits to other file (output file).

What is the problem: Probability idea seem not to be working properly. And more importantly, output file always contains more characters then the original input file, while they should contain equal number of characters.

In this code sample, instead of inverted bits i have put 'x' and 'y', so that it is more obvious that output file contains more characters

INPUT file: 01001

OUTPUT file: xyxxxyx

The code:

void invert_bits(FILE **input, FILE **output, double prob){
srand(clock());
char symbol;
while((symbol = getc(*input)) != EOF){
    double result = rand()/RAND_MAX;
    if(result < prob){
        if(simbol == '0'){
            char bit = 'x';
            fprintf(*output, &bit);
        }
        else{
            char bit = 'y';
            fprintf(*output, &bit);
        }
    }else{
        fprintf(*output, &symbol);
    }
}

}

Upvotes: 2

Views: 985

Answers (2)

Paul
Paul

Reputation: 6911

You aren't using the fprintf function properly.

The function's signature is:

int fprintf ( FILE * stream, const char * format, ... );

Instead of a null terminated string, you're providing it with an address of a char, which might follow by a null character, or might not.

The correct way of printing a character with the *printf functions is:

fprintf(*output, "%c", bit);

P.S. Why are you receiving a pointer to the file handle, i.e. FILE** and not just FILE*?

Upvotes: 1

rici
rici

Reputation: 241901

(f)printf expects a format string as its second argument. You are providing it with the address of a char, which is not even a valid string (since it is not NUL-terminated).

Don't do that. It's a bad habit. When you use printf, fprintf or sprintf always use a format string. (Read this for more information.)

You could have used fprintf(*output, "%c", bit); but it would be a lot simpler to just print the character with fputc(bit, *output);

I don't understand why you feel the need to pass the FILE* arguments as pointers, by the way.

Upvotes: 2

Related Questions