#include <stdio.h>
#include <stdlib.h>
int main()
{
long buffer[]={1000,2000,3000,4000,5000,6000,7000};
long RCV[10]; //接收数组
FILE *fp;
long *fpos = buffer;
long *RCV_pos = RCV;
int num = 0;//统计写入的数据块
int RCV_num = 0;
int nn = 0;//写入时返回的数据块
int n = sizeof(buffer)/sizeof(long);
int a = 0,b = 0;
// wb+ 读写方式打开或建立一个二进制文件,允许读和写
if ((fp=fopen("D:\\Users\\ASUS\\Desktop\\asd.txt","w+"))==NULL)
{
printf("%s\n","can not open file");
exit(0);
}
while(n--)
{
printf("position = %d\t",ftell(fp) );
printf("buffer[i] = %d\t",*fpos );//buffer 中数据的地址,每个四位
printf("fpos = %d\n",fpos ); //输出数组中参数的位置
//nn=fwrite(fpos,sizeof(long),1,fp); //写入文件
fprintf(fp,"%d \n",buffer[a] );
fpos=fpos + 1; //指针位置 +1
//num = num + nn;
a++;
num = num + 1;
}
printf("after write in the file,the ptr's position = %d\t",ftell(fp) );
printf("number of information write = %d\n\n\n",num );
//start read file
rewind(fp);//返回文件首位
while(!feof(fp))/*判断是否结束,这里会有个文件结束符*/
{
//fread(RCV_pos,sizeof(long),1,fp);
fscanf(fp,"%d \n",&RCV[b]);
b++;
RCV_num++;
RCV_pos++;
}
for( int i = 0; i < RCV_num-1; i++)
{
//printf("%d\n",*(RCV_pos-RCV_num + i)); //fpos 存的是buffer地址
printf("%d\n",RCV[i]);
}
return 0;
}
fwrite写入文件乱码,使用fscanf() 和 fprintf() 函数实现
最新推荐文章于 2023-11-26 16:53:41 发布