Consecutive fwrite() not giving desired output

Viewed 77

So I have the following code that I am toying around with:

#include<stdio.h>
#include<stdlib.h>
#include<string.h>

int main (int argc, char* argv[]) {

        FILE* fp;
        char c, currentchar;
        int flag = 0, count = 1;

        if (argc < 2) {
                printf("wzip:insufficient args\n");
                exit(1);
        }
        fp = fopen(argv[1], "r");

        while ( fread(&c, sizeof(char), 1, fp) == 1) {
                if (flag == 1) {
                        if (c == currentchar) {
                                ++count;
                        }
                        else {
                                fwrite(&currentchar, sizeof(char), 1, stdout);
                                //printf("%d", count);
                                fwrite(&count, sizeof(int), 1, stdout);
                                currentchar = c;
                                count = 1;
                        }
                }
                if (flag == 0) {
                        currentchar = c;
                        flag = 1;
                }
        }
        printf("\n");
        return 0;
}

The above code doesn't provide me the output from the second fwrite() function(that uses the count variable). I assume its a problem regarding stream flushing but I can't resolve it. Any help would be great!

E: for a sample input/output, suppose i have a file test.1 that has the letters sssaa in it.

If I run ./wzip test.1 the output is:

sa

while ideally it should be:

s3a2

1 Answers
#include<stdio.h>
#include<stdlib.h>
#include<string.h>

int main (int argc, char* argv[]) {

        FILE* fp;
        char c, currentchar;
        int flag = 0, count = 1;

        if (argc < 2) {
                printf("wzip:insufficient args\n");
                exit(1);
        }
        fp = fopen(argv[1], "r");

        while ( fread(&c, sizeof(char), 1, fp) == 1) {
                if (flag == 1) {
                        if (c == currentchar) {
                                ++count;
                        }
                        else {
                                fwrite(&currentchar, sizeof(char), 1, stdout);
                                //printf("%d", count);
                                fprintf(stdout, "%i", count); /*  this one */
                                currentchar = c;
                                count = 1;
                        }
                }
                if (flag == 0) {
                        currentchar = c;
                        flag = 1;
                }
        }
        printf("\n");
        fclose(fp);
        return 0;
}

Tested 'tcc'. Your fwrite(&count, sizeof(int), 1, stdout); write to stdout not '3' but 0x03 - see ANSII codes . You can check it if call with redirection and check output.file hexviewer. Something like 'wzip test.1 > out.txt'

Related