天天看点

c++对txt文件读取操作+实例代码

因c++文件操作一直要用,所以就特此写一篇博客来记录一下c++对txt文件的读取操作。

1.c++文件流:

fstream   //文件流

ifstream  //输入文件流

ofstream  //输出文件流

2.文件路径的表示

文件路径的表示可以分为绝对路径和相对路径。

绝对路径:pDummyFile = fopen("D:\\vctest\\glTexture\\texture\\dummy.bmp", "rb"); 给出了从盘符开始的全部路径,这里需要注意的是“\”要用双斜线"\\"

相对路径:对相对路径而言,路径表示中的“\”也要用双斜线"\\"

windows下表示相对路径的规则为:

1、.\ 或 ./  表示当前目录,或同级目录;  

 2、..\ 或 ../  表示父目录,或上级目录。

3、文件打开方式选项:

ios::in   //供读,文件不存在则创建(ifstream默认的打开方式)

ios::out   //供写,文件不存在则创建,文件存在则清空原内容(ofstream默认打开方式)

ios::ate  //文件打开时,指针指在文件最后,常和in、out联合使用

ios::app   //供写,文件不存在则创建,在原文件内容后写入新的内容,指针位置总在最后

ios::binary  //二进制格式文件

3、对txt文件的显示和复制(显示in.txt文件内容并将in.txt的内容复制到out.txt文件中)

//实现txt文件的读入并重写入另外一个txt文件中~
#include<fstream>  //ifstream
#include<iostream>
#include<string>     //包含getline()
//#include<cmath>
using namespace std;
int main(){
    string s;
    ofstream outf;
    ifstream inf;
    inf.open("d://in.txt");          //特别注意,这里是://  是双斜杠喔~~ 
    //打开输出文件
    outf.open("d://out.txt");     
    while (getline(inf, s))      //getline(inf,s)是逐行读取inf中的文件信息
    {
        outf << s << '\n';
        cout << s << endl;
    }
    inf.close();
    outf.close();
    return 0;
}
           

4、基本的从txt文件中读入数据和显示数据 

//为能够正确读出写入文件的各数据,各数据间最好要有分隔
#include<iostream>
#include<fstream>
using namespace std;
int main()
{
    fstream f("d:\\out.txt",ios::out);
    f<<1234<<' '<<3.14<<'A'<<"How are you";      //写入数据  
    f.close();
    f.open("d:\\out.txt",ios::in);
    int i;
    double d;
    char c;
    char s[20];
    f>>i>>d>>c;         //读取数据
    f.getline(s,20);
    cout<<i<<endl;       //显示各数据
    cout<<d<<endl;
    cout<<c<<endl;
    cout<<s<<endl;
    f.close();
    return 0;
}
           
// 在文件后面续写数据
#include <iostream>
#include<fstream>
using namespace std;
int main () {
    ofstream examplefile   ("example.txt",ios::app);
    if(examplefile.is_open()) {
        examplefile<<"This is a line.\n";
        examplefile<<"This is another line.\n";
        examplefile.close();
    }
    return 0;
}
           

5、istringstream用法

istringstream对象可以绑定一行字符串,然后以空格为分隔符把该行分隔开来。

#include<iostream>
#include<sstream>
using namespace std;
int main()
{
	string str, line;
	while(getline(cin, line))
	{
		istringstream stream(line);
		while(stream>>str)
			cout<<str.c_str()<<endl;
	}	
	return 0;
}
           

原文:原文链接