C++读写TXT文件

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_27251141/article/details/83054977

C++读写TXT文件

一、文件的输入输出

  fstream提供了三个类,用来实现c++对文件的操作。(文件的创建、读、写)。
  ifstream -- 从已有的文件读入
  ofstream -- 向文件写内容
  fstream - 打开文件供读写
 文件打开模式:
 ios::in             只读
 ios::out            只写
 ios::app            从文件末尾开始写,防止丢失文件中原来就有的内容
 ios::binary         二进制模式
 ios::nocreate       打开一个文件时,如果文件不存在,不创建文件
 ios::noreplace      打开一个文件时,如果文件不存在,创建该文件
 ios::trunc          打开一个文件,然后清空内容
 ios::ate            打开一个文件时,将位置移动到文件尾
 文件指针位置在c++中的用法:
 ios::beg   文件头
 ios::end   文件尾
 ios::cur   当前位置
 例子:
 file.seekg(0,ios::beg);   //让文件指针定位到文件开头 
 file.seekg(0,ios::end);   //让文件指针定位到文件末尾 
 file.seekg(10,ios::cur);   //让文件指针从当前位置向文件末方向移动10个字节 
 file.seekg(-10,ios::cur);   //让文件指针从当前位置向文件开始方向移动10个字节 
 file.seekg(10,ios::beg);   //让文件指针定位到离文件开头10个字节的位置
注意:移动的单位是字节,而不是行。
常用的错误判断方法:
good()   如果文件打开成功
bad()   打开文件时发生错误
eof()    到达文件尾

二、示例

#include <vector>  
#include <string>  
#include <fstream>  
#include <iostream>  

using namespace std;  

int main()  
{  
    ifstream myfile("G:\\C++ project\\Read\\hello.txt");  
    ofstream outfile("G:\\C++ project\\Read\\out.txt", ios::app);  
    string temp;  
    if (!myfile.is_open())  
    {  
        cout << "未成功打开文件" << endl;  
    }  
    while(getline(myfile,temp))  
    {  
        outfile << temp;  
        outfile << endl;
    }  
    myfile.close();  
    outfile.close();
    return 0;  
} 

猜你喜欢

转载自blog.csdn.net/qq_27251141/article/details/83054977