user3226932
user3226932

Reputation: 2232

fwrite in C giving different values in output files

why are the output files different when I use fwrite in another function VERSUS fwrite in the same function?

output1.txt contains garbage value like Ê, which is NOT correct

output2.txt contains "b", which is correct

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

void writeData(char *buf, char *path) {
    FILE *fp1;
    fp1 = fopen(path, "a");
    fwrite(&buf, sizeof(char), strlen(buf), fp1);
}

int main () {


    char buf[2] = "a";
    char buf2[3] = "yb";
    char file1_path[12] = "output1.txt";
    char file2_path[12] = "output2.txt";
    memset(buf, 0, sizeof(buf));
    memcpy(buf, &buf2[1], strlen(buf2));
    printf("%s\n", buf);

    writeData(buf, file1_path);

    FILE *fp2;
    fp2 = fopen(file2_path, "a");
    fwrite(&buf, sizeof(char), strlen(buf), fp2);

   return(0);
}

Upvotes: 1

Views: 378

Answers (3)

eca
eca

Reputation: 21

writeData() should call fwrite(buf, ...) not fwrite(&buf, ...)

Upvotes: 1

Some programmer dude
Some programmer dude

Reputation: 409176

In the writeData function, in your call to fwrite:

fwrite(&buf, sizeof(char), strlen(buf), fp1);

the variable buf is a pointer to the first character in the string to write. It's of typechar *. However the expression &buf is a pointer to the variable buf, its type is char **. It's not the same data.


It works if buf is an array because both then buf (which is really &buf[0]) and &buf points to the same location. They are still different types though.

For example with

char buf[2];

then buf decays to a pointer to the arrays first element (i.e. &buf[0]) and is of type char *. The expression &buf is a pointer to the array and is of type char (*)[2].

Somewhat graphically

+--------+--------+
| buf[0] | buf[1] |
+--------+--------+
^
|
&buf[0]
|
&buf

Two pointers to the same location, but different types and different semantic meanings.

Upvotes: 2

Varun
Varun

Reputation: 477

In function writeData change

fwrite(&buf, sizeof(char), strlen(buf), fp1);

to

fwrite(buf, sizeof(char), strlen(buf), fp1);

Upvotes: 2

Related Questions