C++文件读写

来源:互联网 发布:网络可靠性评估协议 编辑:程序博客网 时间:2024/06/16 06:23
#include<iostream>
#include<string>//字符串
#include<fstream>//文件读写

using namespace std;

void fun(char *a, char *b, long &c)
{
c =static_cast<long> (a[1] - '0');
c = c * 10 + (b[1] -  '0');
}
void filewrite()
{
fstream fw("test.txt", ios::out |ios::binary);
if (!fw)
{
cout << "写入失败" << endl;
}
int a = 45;
int b = 12;

//以字符串形式写入一个int变量或字符串到文件
fw << a << endl;
fw << b << endl;

//以字符形式写入一个int变量或单个字符到文件
fw.put(a);
fw.put(b);

fw.close();//关闭文件
}
void fileread()
{
fstream fr("test.txt", ios::in);
if (!(fr.operator bool()))
{
cout << "读取失败" << endl;
}
char a[64] = { 0 };
char b[64] = { 0 };
char buf[1024] = { 0 };

while (!fr.eof())   //判断文件是否读取到结束,结束返回“非0”未结束返回“0”
{
fr.getline(a,sizeof(a));  // 读取一行字符数组a大小的空间到字符数组a
fr.getline(b,sizeof(b));

fr.seekg(0, ios::beg);
fr.read(buf, sizeof(buf));  //读取一块字符数组buf1大小的空间到字符数组buf

cout << a << endl <<  b << endl;
cout << buf << endl;
}

long c = 0;
fun(a, b, c);
cout << c << endl;
fr.close();//关闭文件
}
int main()
{
filewrite();
fileread();

system("pause");
return 0;
}
0 0