2-文件的读写

#include <iostream>
#include <fstream>
using namespace std;

void main()
{
    ofstream in;
    in.open("com.txt",ios::trunc); //ios::trunc表示在打开文件前将文件清空,由于是写入,文件不存在则创建
    int i;
    char a='a';
    for(i=1;i<=26;i++)//将26个数字及英文字母写入文件
    {
        if(i<10)
        {
            in<<"0"<<i<<"\t"<<a<<"\n";
            a++;
        }
        else
        {
            in<<i<<"\t"<<a<<"\n";
            a++;
        }
    }
    in.close();//关闭文件
}


#include <iostream>
#include <fstream>
using namespace std;

void main()
{
    char buffer[256];
    fstream out;
    out.open("com.txt", ios::in);
    cout << "com.txt" << " 的内容如下:" << endl;
    while (!out.eof())
    {
        out.getline(buffer, 256, '\n');//getline(char *,int,char) 表示该行字符达到256个或遇到换行就结束
        cout << buffer << endl;
    }
    out.close();
    cin.get();//cin.get() 是用来读取回车键的,如果没这一行,输出的结果一闪就消失了
}

  

猜你喜欢

转载自www.cnblogs.com/zhumengdexiaobai/p/9362290.html