C++ 【第二篇】文件操作(二)
文件操作
文件类型分为两种:
- 
文本文件 - 文件以文本的ASCII码形式存储在计算机中
 - 
二进制文件 - 文件以文本的二进制形式存储在计算机中,用户一般不能直接读懂它们
 
1文本文件

#include <fstream> void test01() { ofstream ofs; ofs.open("test.txt", ios::out); ofs << "姓名:张三" << endl; ofs << "性别:男" << endl; ofs << "年龄:18" << endl; ofs.close(); } int main() { test01(); system("pause"); return 0; }
#include <fstream> #include <string> void test01() { ifstream ifs; ifs.open("test.txt", ios::in); if (!ifs.is_open()) { cout << "文件打开失败" << endl; return; } //第一种方式 //char buf[1024] = { 0 }; //while (ifs >> buf) //{ // cout << buf << endl; //} //第二种 //char buf[1024] = { 0 }; //while (ifs.getline(buf,sizeof(buf))) //{ // cout << buf << endl; //} //第三种 //string buf; //while (getline(ifs, buf)) //{ // cout << buf << endl; //} char c; while ((c = ifs.get()) != EOF) { cout << c; } ifs.close(); } int main() { test01(); system("pause"); return 0; }
#include <iostream> using namespace std; #include <fstream> #define FILENAME "File.txt" //文件写 void file_w() { ofstream ofs; ofs.open(FILENAME, ios::out); //w模式打开文件 for (int i = 0; i < 3; i++) { ofs <<10 << " " << 20 << " " << 30 << endl; } ofs.close(); } //文件读 void file_r() { ifstream ifs; ifs.open(FILENAME, ios::in); int id; string name; int dId; int index = 0; while (ifs >> id && ifs >> name && ifs >> dId) { cout<<id<<" " <<name<<" " <<dId<<endl; } } //清空文件 void file_trunc() { cout << "确认清空?" << endl; cout << "1、确认" << endl; cout << "2、返回" << endl; int select = 0; cin >> select; if (select == 1) { // ios::trunc 如果存在删除文件并重新创建 ofstream ofs(FILENAME, ios::trunc); ofs.close(); cout << "清空成功!" << endl; } system("pause"); //system("cls"); } void file_add(){ //追加方式打开 ofstream ofs(FILENAME, ios::app); ofs <<"追加内容" << " " << 20 << " " << 30 << endl; } int main(){ file_w(); //file_r(); //file_trunc(); file_add(); return 0; } //g++ main.cpp emplo
2 二进制文件
#include <fstream> #include <string> class Person { public: char m_Name[64]; int m_Age; }; //二进制文件 写文件 void test01() { //1、包含头文件 //2、创建输出流对象 ofstream ofs("person.txt", ios::out | ios::binary); //3、打开文件 //ofs.open("person.txt", ios::out | ios::binary); Person p = {"张三" , 18}; //4、写文件 ofs.write((const char *)&p, sizeof(p)); //5、关闭文件 ofs.close(); } int main() { test01(); system("pause"); return 0; }
#include <fstream> #include <string> class Person { public: char m_Name[64]; int m_Age; }; void test01() { ifstream ifs("person.txt", ios::in | ios::binary); if (!ifs.is_open()) { cout << "文件打开失败" << endl; } Person p; ifs.read((char *)&p, sizeof(p)); cout << "姓名: " << p.m_Name << " 年龄: " << p.m_Age << endl; } int main() { test01(); system("pause"); return 0; }
    作者:华王
博客:https://www.cnblogs.com/huahuawang/
                    
                
                
            
        
浙公网安备 33010602011771号