C# · 12月 20, 2021

c,c++读写文本,二进制方法

#include “stdafx.h”

#include

#include

#include

#include

#include

using namespace std;

#pragma warning(disable:4996)

void WriteTXTFile_C()

{

FILE * fp = fopen(“c.txt”,”wt”);

for (int i = 0; i < 1000; i++)

{

for (int j = 0; j < 1000; j++)

{

fputc(‘C’,fp);

fputs(“Hello World!n”,fp);

}

}

fclose(fp);

}

void ReadTXTFile_C()

{

FILE* fp = fopen(“c.txt”,”rt”);

char str[15];

for (int i = 0; i < 1000; i++)

{

for (int j = 0; j < 1000; j++)

{

fgetc(fp);

fgets(str,15,fp);

}

}

fclose(fp);

}

void WriteBINFile_C()

{

FILE* fp = fopen(“d.bin”,”wb”);

const char* str = “CHello,worldn”;

int len = strlen(str);

for (int i = 0; i < 1000; i++)

{

for (int j = 0; j < 1000; j++)

{

fwrite(str,1,len,fp);

}

}

fclose(fp);

}

void ReadBINFile_C()

{

FILE* fp = fopen(“d.bin”,”rb”);

char str[16];

for (int i = 0; i < 1000; i++)

{

for (int j = 0; j < 1000; j++)

{

fread(str,16,fp);

}

}

fclose(fp);

}

void WriteTXTFile_CPlus()

{

fstream file;

file.open(“cp.txt”,ios::in | ios::out | ios::trunc);//注意ios::in,或者ios::in | ios::out两种方式在文件不存在时会执行写操作但不会建立文件。

for(int i=0;i<1000;i++)

{

for (int j = 0; j < 1000; j++)

{

file.put(‘C’);

file << "Hello,worldn";

}

}

file.close();

}

void ReadTXTFile_CPlus()

{

fstream file;

file.open(“cp.txt”,ios::in|ios::out);

char str[15];

for (int i = 0; i < 1000; i++)

{

for(int j=0;j<1000;j++)

{

file.get(str,15);

}

}

file.close();

}

void WriteBINFile_CPlus()

{

fstream file;

file.open(“cp.bin”,ios::in | ios::out | ios::trunc | ios::binary);

const char* str = “CHello World!n”;

int len = strlen(str);

for (int i = 0; i < 1000; i++)

{

for (int j = 0; j < 1000; j++)

{

file.write(str,len);

}

}

file.close();

}

void ReadBINFile_CPlus()

{

fstream file;

file.open(“d.bin”,ios::in | ios::out | ios::binary);

char str[16];

for (int i = 0; i < 1000; i++)

{

for (int j = 0; j < 1000; j++)

{

file.read(str,16);

}

}

file.close();

}