码迷,mamicode.com
首页 > 编程语言 > 详细

C++ 文件IO

时间:2021-05-25 17:43:44      阅读:0      评论:0      收藏:0      [点我收藏+]

标签:info   c++   ret   func   ace   ini   exe   cout   feed   

在C++中标准库提供三个类用于文件操作,统称为文件流类:

  • ifstream:专用于从文件中读取数据;
  • ofstream:专用于向文件中写入数据;
  • fstream:既可用于从文件中读取数据,又可用于向文件中写入数据。

这三个文件流类都位于 头文件中,因此在使用它们之前,需要先引入此头文件。

有两种方式可以打开文件

1、在构造函数中传入文件名

ifstream (const char* filename, ios_base::openmode mode = ios_base::in);
ifstream fin(filename, openmode) by default openmode = ios::in
ifstream fin(“filename”);

2、使用open方法

Calling of default constructor
ifstream fin;

fin.open(filename, openmode)
fin.open(“filename”);

打开方式:

模式标记 适用对象 作用
ios::in ifstream、fstream 打开文件用于读取数据。如果文件不存在,则打开出错。
ios::out ofstream、fstream 打开文件用于写入数据。如果文件不存在,则新建该文件;如果文件原来就存在,则打开时清除原来的内容。
ios::app ofstream、fstream 打开文件,用于在其尾部添加数据。如果文件不存在,则新建该文件。
ios::ate ifstream 打开一个已有的文件,并将文件读指针指向文件末尾(读写指 的概念后面解释)。如果文件不存在,则打开出错。
ios:: trunc ofstream 打开文件时会清空内部存储的所有数据,单独使用时与 ios::out 相同。
ios::binary ifstream、ofstream、fstream 以二进制方式打开文件。若不指定此模式,则以文本模式打开。
ios::in | ios::out fstream 打开已存在的文件,既可读取其内容,也可向其写入数据。文件刚打开时,原有内容保持不变。如果文件不存在,则打开出错。
ios::in | ios::out ofstream 打开已存在的文件,可以向其写入数据。文件刚打开时,原有内容保持不变。如果文件不存在,则打开出错。
ios::in | ios::out | ios::trunc fstream 打开文件,既可读取其内容,也可向其写入数据。如果文件本来就存在,则打开时清除原来的内容;如果文件不存在,则新建该文件。

使用 ifsream & ofstream classes实现文件读写的Demo:

#include <iostream>
  
/* fstream header file for ifstream, ofstream, 
  fstream classes */
#include <fstream>
  
using namespace std;
  
// Driver Code
int main()
{
    // Creation of ofstream class object
    ofstream fout;
  
    string line;
  
    // by default ios::out mode, automatically deletes
    // the content of file. To append the content, open in ios:app
    // fout.open("sample.txt", ios::app)
    fout.open("sample.txt");
  
    // Execute a loop If file successfully opened
    while (fout) {
  
        // Read a Line from standard input
        getline(cin, line);
  
        // Press -1 to exit
        if (line == "-1")
            break;
  
        // Write line in file
        fout << line << endl;
    }
  
    // Close the File
    fout.close();
  
    // Creation of ifstream class object to read the file
    ifstream fin;
  
    // by default open mode = ios::in mode
    fin.open("sample.txt");
  
    // Execute a loop until EOF (End of File)
    while (fin) {
  
        // Read a Line from File
        getline(fin, line);
  
        // Print line in Console
        cout << line << endl;
    }
  
    // Close the file
    fin.close();
  
    return 0;
}

使用fstream class实现文件读写的demo:

#include <iostream>
  
/* fstream header file for ifstream, ofstream, 
   fstream classes */
#include <fstream>
  
using namespace std;
  
// Driver Code
int main()
{
    // Creation of fstream class object
    fstream fio;
  
    string line;
  
    // by default openmode = ios::in|ios::out mode
    // Automatically overwrites the content of file, To append
    // the content, open in ios:app
    // fio.open("sample.txt", ios::in|ios::out|ios::app)
    // ios::trunc mode delete all conetent before open
    fio.open("sample.txt", ios::trunc | ios::out | ios::in);
  
    // Execute a loop If file successfully Opened
    while (fio) {
  
        // Read a Line from standard input
        getline(cin, line);
  
        // Press -1 to exit
        if (line == "-1")
            break;
  
        // Write line in file
        fio << line << endl;
    }
  
    // Execute a loop untill EOF (End of File)
    // point read pointer at beginning of file
    fio.seekg(0, ios::beg);
  
    while (fio) {
  
        // Read a Line from File
        getline(fio, line);
  
        // Print line in Console
        cout << line << endl;
    }
  
    // Close the file
    fio.close();
  
    return 0;
}

使用read、write方法读写文件,其语法如下:

To write object‘s data members in a file :
// Here file_obj is an object of ofstream
file_obj.write((char *) & class_obj, sizeof(class_obj));

To read file‘s data members into an object :
// Here file_obj is an object of ifstream
file_obj.read((char *) & class_obj, sizeof(class_obj));

Example:

Input : 
Input.txt :
Michael 19 1806
Kemp 24 2114
Terry 21 2400
Operation : Print the name of the highest 
            rated programmer.

Output : 
Terry

demo:

#include <iostream>
#include <fstream>
using namespace std;
 
// Class to define the properties
class Contestant {
public:
    // Instance variables
    string Name;
    int Age, Ratings;
 
    // Function declaration of input() to input info
    int input();
 
    // Function declaration of output_highest_rated() to
    // extract info from file Data Base
    int output_highest_rated();
};
 
// Function definition of input() to input info
int Contestant::input()
{
    // Object to write in file
    ofstream file_obj;
 
    // Opening file in append mode
    file_obj.open("Input.txt", ios::app);
 
    // Object of class contestant to input data in file
    Contestant obj;
 
    // Feeding appropriate data in variables
    string str = "Michael";
    int age = 18, ratings = 2500;
 
    // Assigning data into object
    obj.Name = str;
    obj.Age = age;
    obj.Ratings = ratings;
 
    // Writing the object‘s data in file
    file_obj.write((char*)&obj, sizeof(obj));
 
    // Feeding appropriate data in variables
    str = "Terry";
    age = 21;
    ratings = 3200;
 
    // Assigning data into object
    obj.Name = str;
    obj.Age = age;
    obj.Ratings = ratings;
 
    // Writing the object‘s data in file
    file_obj.write((char*)&obj, sizeof(obj));
 
    return 0;
}
 
// Function definition of output_highest_rated() to
// extract info from file Data Base
int Contestant::output_highest_rated()
{
    // Object to read from file
    ifstream file_obj;
 
    // Opening file in input mode
    file_obj.open("Input.txt", ios::in);
 
    // Object of class contestant to input data in file
    Contestant obj;
 
    // Reading from file into object "obj"
    file_obj.read((char*)&obj, sizeof(obj));
 
    // max to store maximum ratings
    int max = 0;
 
    // Highest_rated stores the name of highest rated contestant
    string Highest_rated;
 
    // Checking till we have the feed
    while (!file_obj.eof()) {
        // Assigning max ratings
        if (obj.Ratings > max) {
            max = obj.Ratings;
            Highest_rated = obj.Name;
        }
 
        // Checking further
        file_obj.read((char*)&obj, sizeof(obj));
    }
 
    // Output is the highest rated contestant
    cout << Highest_rated;
    return 0;
}
 
// Driver code
int main()
{
    // Creating object of the class
    Contestant object;
 
    // Inputting the data
    object.input();
 
    // Extracting the max rated contestant
    object.output_highest_rated();
 
    return 0;
}

C++ 文件IO

标签:info   c++   ret   func   ace   ini   exe   cout   feed   

原文地址:https://www.cnblogs.com/Yuanb/p/14805819.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!