大哥大姐们帮忙看看这个很短的C语言程序为啥错了好不好?

来源:百度知道 编辑:UC知道 时间:2024/09/21 10:39:05
#include<stdio.h>
#include<stdlib.h>

main()
{
int a;
printf("hello");
scanf("%d",&a);
printf("%d",a);

FILE *fp; /*指向文件的指针*/
if((fp=fopen("kc1.txt","w"))==NULL) /*创建并打开文件kc*/
{
printf("Cannot open this file!\n");
exit(0);
}

if(fwrite(a,sizeof(int),1,fp)!=1)
printf("File write error!\n");
fclose(fp); /*关闭文件*/

}
确实应该把变量写在前面,然后加上&a,我是学C++的,哪知道C语言这些要求啊,五楼你牛什么呀,但是改过以后为什么文件里不显示输入a的值呢?

回答这个问题:但是改过以后为什么文件里不显示输入a的值呢?
因为fwrite是以二进制写入文件的。所以你看到的是类似乱码的东西。
可以用fprintf格式化写入文件。
这样,我在你代码的基础上改了下,你可以看下fprintf的用法:
#include<stdio.h>
#include<stdlib.h>

main()
{
int a;
FILE *fp; /*指向文件的指针*/
printf("hello");
scanf("%d",&a);
printf("%d",a);

if((fp=fopen("d:\\kc1.txt","w"))==NULL) /*创建并打开文件kc*/
{
printf("Cannot open this file!\n");
exit(0);
}

// if(fwrite(&a,sizeof(int),1,fp)!=1)
if(fprintf(fp,"%d",a)<0) //用fprintf格式化写入文件
printf("File write error!\n");
fclose(fp); /*关闭文件*/

}

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

main()
{
int a;
printf("hello");
scanf("%d",&a);
printf("%d",a);

FILE *fp; /*指向文件的指针*/