C中二进制方式读取写入文件简单实验

来源:互联网 发布:土木工程翻译软件 编辑:程序博客网 时间:2024/06/05 19:50
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
using namespace std;
int main(int argc, char* argv[])
{
 char *strArr = new char[2];
 FILE* file1 = fopen("C:\\Users\\Administrator\\Desktop\\a.txt", "r");
 FILE* file2 = fopen("C:\\Users\\Administrator\\Desktop\\b.txt", "w+");
 int a=fread(strArr, 1, 2, file1);
 while (a==2)
 {
  int b=fwrite(strArr, 1, 2, file2);
  if (b==2)
  {
   cout << "往ffile2中写入的就是2" << endl;
  }
  memset(strArr, 0, 2);
  a = fread(strArr, 1, 2, file1);
  cout << "a:" << a << endl;
  if (a<2)
  {
      fread(strArr, 1, a, file1);
     int b=fwrite(strArr, 1, a, file2);
     cout << "往file2中写入的就是:"<<a << endl;
     cout << "往file2中写入的就是:" << b<< endl;
  }
 }
 fclose(file1);
 fclose(file2);
 delete[] strArr;


 ////以二进制的形势读取文件
 //FILE* file = fopen("C:\\Users\\Administrator\\Desktop\\a.txt", "r"); //文件指针
 //FILE* file2 = fopen("C::\\Users\\Administraror\\Desktop\\new.txt", "w+");//文件指针
 ////二进制形式读取数据
 //char* bufferArr =new char[4];//开辟5个字节
 //memset(bufferArr, 0, 4);
 ////正常返回的话,是实际输出的数据块个数,也就是count,这里是1.
 //int a=fread(bufferArr, 1, 3, file);
 //while (a)
 //{
 // cout << a << endl;
 // if (a==3){
 //  //cout << bufferArr << endl;
 //  int b=fwrite(bufferArr, 1, 1, file2);
 // }
 // else
 // {
 //  fread(bufferArr, 1, a, file);
 //  //cout << bufferArr << endl;
 //  fwrite(bufferArr, 1, 1, file2);
 // }
 // memset(bufferArr, 0, 4);
 // a = fread(bufferArr, 1, 3, file);
 //}
 //fclose(file);
 //fclose(file2);
 system("pause");
 return 0;
}


//cout << bufferArr << endl;
//写入到另外的一个文件中
/* if (fwrite(bufferArr, 5, 1, file2)==1)
{
memset(bufferArr, 0, 5);
}
else
{
cout << "写入不成功" << endl;
}*/

//memset(bufferArr, 0, 4);

2个函数的说明:
读取函数
int fread(void* buffer,int size;int count,File* file);
file:关联一个文件;进行读取数据
buffer:缓冲区,将文件中的数据读入进去
size:一个数据块多大,根据自己的要求设置吧。
count:一次读取几个数据块。
返回值,读取的块数。count。
写入函数
int fwrite(void* buffer,int size,int count,File* file);
buffer:写入到文件中的数据 缓冲池
size: 数据块的大小
count:数据块的个数
file:关联的文件。
返回值:写入块数。


1 0
原创粉丝点击