/*
* FostreamTester.h
*
* Created on: 2014-9-1
* Author: blade
*/
#ifndef FOSTREAMTESTER_H_
#define FOSTREAMTESTER_H_
#include <fstream>
using namespace std;
class FstreamTester {
public:
int readFromFile(string file);
int writeToFile(string file);
};
#endif /* FOSTREAMTESTER_H_ */
头文件,文件读写简单的测试,其中写入文件折腾了半个小时。郁闷死了。
/*
* FstreamTester.cc
*
* Created on: 2014-9-1
* Author: blade
*/
#include "FstreamTester.h"
#include <fstream>
#include <iostream>
using namespace std;
/**
* 从文件中读取出来
*/
int FstreamTester::readFromFile(string file) {
ifstream infile(file.c_str());
string showText;
if (!infile) {//检查文件是否开打成功
cerr << "文件打开失败:" << infile << endl;
cout << "输入任意继续:" << endl;
string GO_ON;
cin >> GO_ON;
return -1;
}
infile.close();
infile.open(file.c_str());//
if (infile.is_open()) {
cout << " 文件打开成功! " << endl;
while (infile.good() && !infile.eof()) {
infile >> showText;
cout << showText << endl;
}
}else{
cout << " 文件打开失败! " << endl;
return -1;
}
infile.close();
cout << "输入任意继续:" << endl;
string GO_ON;
cin >> GO_ON;
return 0;
}
/**
* 写到文件中去
*/
int FstreamTester::writeToFile(string file) {
ofstream outfile(file.c_str());
if (!outfile) {//检查文件是否开打成功
cerr << "文件准备失败:" << outfile << endl;
cout << "输入任意继续:" << endl;
string GO_ON;
cin >> GO_ON;
return -1;
}
outfile.close();//这句是必要的,要不然,写入内容为空,暂时不太清楚为什么
outfile.open(file.c_str());
if (outfile.is_open()) {
cout << " 文件打开成功! " << endl;
outfile << "This is a line.\n" << endl;
outfile << "This is another line.\n"<< endl;
outfile.close();
} else {
cerr << "文件打开失败:" << outfile << endl;
return -1;
}
cout << "输入任意继续:" << endl;
string GO_ON;
cin >> GO_ON;
return 0;
}
实现类的两个成员函数,readFromFile(string file),writeToFile(string file),里边有好多要注意的地方:
1.开打文件时,调用close()方法,解除文件关联。
2.执行读写操作前,判断文件是否打开,执行读写后,要close();//有点幼稚,但确实需要注意
3.标准库ifstream,ofstream使用的是c风格的字符串。
//============================================================================
// Name : IOTest.cpp
// Author : blade
// Version :
// Copyright : Your copyright notice
// Description : Hello World in C++, Ansi-style
//============================================================================
#include <iostream>
#include "FstreamTester.h"
using namespace std;
int testFostream(){
cout << "从文件读取文本开始:" <<endl;
FstreamTester *ft = new FstreamTester();
string fromfile("C:/Users/blade/workspace/IOTest/src/abc.txt");
ft->readFromFile(fromfile);
cout << "读取结束:" <<endl;
cout << "写入文本到文件开始:" <<endl;
string tofile("C:/Users/blade/workspace/IOTest/src/out.txt");
int flag = ft->writeToFile(tofile);
if(flag == -1){
cout << "写入失败,结束:" <<endl;
}
return 0;
}
void showMenu(){
cout << "欢迎,请输入相应的数字运行相应的程序:\n" << endl;
cout << "1.文件流测试." << endl;
cout << "2." << endl;
cout << "3." << endl;
cout << "4." << endl;
cout << "5." << endl;
cout << "6." << endl;
}
int main() {
showMenu();
string index;
cin >> index;
if(index == "1"){
return testFostream();
}
showMenu();
return 0;
}
main函数文件,用于列表选择操作,方便管理进入测试方法。