在C中使用fwrite在输出文件中提供不同的值 [英] fwrite in C giving different values in output files
问题描述
当我在另一个函数中使用fwrite相对于同一函数中的fwrite时,为什么输出文件不同?
why are the output files different when I use fwrite in another function VERSUS fwrite in the same function?
output1.txt包含垃圾值,例如Ê,不是正确
output1.txt contains garbage value like Ê, which is NOT correct
output2.txt包含 b,这是正确的
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);
}
推荐答案
在 writeData
函数,在调用 fwrite
时:
fwrite(&buf, sizeof(char), strlen(buf), fp1);
变量 buf
是指向字符串中的第一个字符。类型为 char *
。但是,表达式& buf
是指向变量 buf
的指针,其类型为 char **
。数据不同。
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.
如果 buf
为一个 array ,因为它们都同时是 buf
(实际上是& buf [0]
)和& buf
指向同一位置。但是它们仍然是不同的类型。
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.
例如
char buf[2];
然后 buf
衰变指向数组第一个元素(即<$ c $ c>& buf [0] )的指针,其类型为 char *
。表达式& buf
是指向数组的指针,类型为 char(*)[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]
.
图形化
+--------+--------+
| buf[0] | buf[1] |
+--------+--------+
^
|
&buf[0]
|
&buf
两个指向同一位置,但类型和语义不同的指针。
Two pointers to the same location, but different types and different semantic meanings.
这篇关于在C中使用fwrite在输出文件中提供不同的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!