您的位置:首页 > 编程语言 > C语言/C++

C++中文件流操作

2017-04-06 11:54 197 查看

一、C++中流和流操作符

  C++中把数据之间的传输操作称为流,流既可以表示数据从内存传送到某个载体或设备中,即输出流,也可以表示数据从某个载体或设备传送到内存缓冲区变量中,即输入流。C++输入输出除了read和write函数,还提供流操作符,可以重在,输入流操作符">>"和输出流操作符"<<"。

标准I/O流:内存与标准输入输出设备之间信息的传递;《iostream》

文件I/O流:内存与外部文件之间信息的传递;《fstream》

字符串I/O流:内存变量与表示字符串流的字符数组之间信息的传递《sstream》

二、文件流的基本操作

  1.确定文件打开的模式。可以选的模式主要有:

ios::in 为输入(读)而打开一个文件
ios::out 为输出(写)而打开文件
ios::ate 初始位置:文件尾
ios::app 所有输出附加在文件末尾
ios::trunc 如果文件已存在则先删除该文件
ios::binary 二进制方式

  2.默认情况下是以文本的方式写文件,并且会删除原本文件中的数据,即ios::trunc

  3.判断文件是否正常打开。好的文件操作习惯是,每次打开一个文件后,在进行文件写之前要判断文件是否正常打开,使用的函数是is_open()。

  4.文件写。主要有下面三函数,<< 流操作符,写一个字符put(),写一块数据write;

std::ostream::operator<<
std::ostream::put
std::ostream::write

5.文件读。主要有流操作符>>,读一个字符get,读一行getline,读文件中一块read

std::istream::operator>>
istream& operator>> (int& val);
std::istream::getline
istream& getline (char* s, streamsize n );
istream& getline (char* s, streamsize n, char delim );
std::getline (string)
istream& getline (istream& is, string& str, char delim);
istream& getline (istream& is, string& str);
std::istream::read
istream& read (char* s, streamsize n);
std::istream::get
istream& get (char& c);

6.文件结尾的判断 infile.eof()

7.文件关闭 infile.close()

8.文件定位 seekp(),seekg()

9.文件修改,见实例

1.1 文件写

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

using namespace std;
int main() {
/*
* ios::app:添加,ios::trunc:如果文件存在,先删除该文件(默认)
* bios::binary 二进制方式读写,默认是文本方式
*/
ofstream outfile("testfile.txt",ios::out | ios::trunc);
if(!outfile.is_open()){
cerr << "file cannot open!" << endl;
return -1;
}

outfile << "This is a test.\n";
outfile << 100 << endl;

outfile.put('c');  // write a char.
outfile.put('\n');

char buffer[1024] = "abc";
outfile.write(buffer,sizeof(buffer)); // write a block.

outfile.close();

return 0;
}


1.2 文件读

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

using namespace std;
int main() {

ifstream infile("testfile.txt");
if (!infile.is_open()) {
cerr << "file cannot open!" << endl;
return -1;
}

//读一个字符
char ch;
infile.get(ch);

//读一个字符串
string word;
infile >> word;

//读一行 常用
infile.seekg(0);
string line;
getline(infile, line);

char buffer[1024];
infile.seekg(0); //定位到文件头
infile.getline(buffer, sizeof(buffer));

//读文件块
infile.seekg(0);
infile.read(buffer, sizeof(buffer));

//判断文件结尾
infile.seekg(0);
while (!infile.eof()) {
getline(infile,line);
//        infile >> word;
//        infile.read(buffer,sizeof(buffer));
}

infile.close();
return 0;
}


1.3 文件内容修改

#include <fstream>

using namespace std;
int main() {
fstream inOutFile("testfile.txt",ios::in | ios::out);
inOutFile.seekg(50);
inOutFile << "修改文件很容易!\n";
inOutFile.close();
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: