fwrite in C giving different values in output files

ぐ巨炮叔叔 提交于 2019-12-31 04:21:38

问题


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);
}

回答1:


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.




回答2:


In function writeData change

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

to

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



回答3:


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



来源:https://stackoverflow.com/questions/46997747/fwrite-in-c-giving-different-values-in-output-files

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!