standard_in and standard_out
- standard_in (key_board) - standard_out (screen)
C和C++输入输出的比较
#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include<string>
#include<fstream>
using namespace std;
void TestCWrite(int ar[], int n)
{
FILE *fp = fopen("Test1.txt", "w");
if(fp == NULL)
{
return;
}
for(int i=0; i<n; ++i)
{
fprintf(fp, "%d ", ar[i]); //格式化输出
}
fclose(fp);
}
void TestCRead(int ar[], int n)
{
FILE *fp = fopen("Test1.txt", "r");
if(fp == NULL)
return;
for(int i=0; i<n; ++i)
{
(void)fscanf(fp, "%d", &ar[i]); //格式化输入
}
fclose(fp);
}
void TestCppWrite(int ar[], int n)
{
//ofstream ofile; //1
//ofile.open("Test2.txt", ios::out); //2
ofstream ofile("Test3.txt", ios::out); //1+2
if(!ofile)
{
cout<<"Open File Error."<<endl;
return;
}
for(int i=0; i<n; ++i)
{
ofile<<ar[i]<<" "; //3
}
ofile.close(); //4
}
void TestCppRead(int ar[], int n)
{
ifstream ifile;
ifile.open("Test2.txt", ios::in);
if(!ifile)
return;
for(int i=0; i<n; ++i)
{
ifile>>ar[i];
}
ifile.close();
}
//
//二进制文件
void TestCBinWrite(int ar[], int n)
{
FILE *fp = fopen("Test3.txt", "wb");
if(fp == NULL)
{
return;
}
fwrite(ar, sizeof(int), n, fp); //C
fclose(fp);
}
void TestCBinRead(int ar[], int n)
{
FILE *fp = fopen("Test3.txt", "rb");
if(fp == NULL)
return;
fread(ar, sizeof(int), n, fp);
fclose(fp);
}
void TestCppBinWrite(int ar[], int n)
{
//ofstream ofile; //1
//ofile.open("Test2.txt", ios::out); //2
ofstream ofile("Test4.txt", ios::out|ios::binary);
if(!ofile)
{
cout<<"Open File Error."<<endl;
return;
}
ofile.write((const char*)ar, sizeof(int) * n);
ofile.close(); //4
}
void TestCppBinRead(int ar[], int n)
{
ifstream ifile;
ifile.open("Test4.txt", ios::in|ios::binary);
if(!ifile)
return;
ifile.read((char*)ar, sizeof(int) * n);
ifile.close();
}
void main()
{
int ar[] = {12,23,34,45,56,67,78,89,90,100};
int n = sizeof(ar) / sizeof(int);
//TestCWrite(ar, n);
//TestCppWrite(ar, n);
int br[10];
int cr[10];
//TestCRead(br, 10);
//TestCppRead(cr, 10);
//TestCBinWrite(ar, n);
//TestCppBinWrite(ar, n);
TestCBinRead(br, 10);
TestCppBinRead(cr, 10);
}
随机读写fseek
void main()
{
FILE *fp = fopen("Test1.txt","r");
int pos = 1;
int value;
while(1)
{
cout<<"input pos:>";
cin>>pos;
fseek(fp, pos*3, SEEK_SET);
(void)fscanf(fp, "%d", &value);
printf("value = %d\n", value);
}
fclose(fp);
}
setwidth
uperr