getString.cpp
/*
* Please input the input file name
* /Users/brown/Documents/C:C++/IO/IO/output.txt
* 青春的土壤中,只有记忆是潮湿的,我们不是植物,不能在这片土壤中生生不息。
* 很多人问我,青春的诀别是否意味着年迈的将近,其实青春它一直都在继续。
*/
#include <iostream>
#include <fstream>
void getInputStream(std::ifstream& outFile);
int main() {
using std::cout;
using std::string;
std::ifstream outFile;
string s;
getInputStream(outFile);
while (outFile >> s)
cout << s;
outFile.close();
return 0;
}
void getInputStream(std::ifstream& outFile) {
char outPut[50] ;
std::cout << "Please input the input file name\n";
std::cin >> outPut;
outFile.open(outPut);
if (outFile.fail()) {
std::cout << outPut << "opening fail.\n";
exit(EXIT_FAILURE);
}
}
getInt.cpp
// 1 + 2 + 3 + 4 + 5 = 15
#include <iostream>
#include <fstream>
int main() {
using std::cout;
using std::cin;
std::ifstream inFile;
int x, sum = 0;
inFile.open("/Users/br/Documents/C:C++/IO/IO/input.txt");
if (inFile.fail()) {
std::ofstream inData;
inData.open("/Users/br/Documents/C:C++/IO/IO/input.txt");
if (inData.fail()) {
cout << "inData opening file failed.";
exit(EXIT_FAILURE);
}
}
while (inFile >> x)
sum += x;
cout << "1 + 2 + 3 + 4 + 5 = " << sum;
std::ofstream outFile;
/* 按照书上的说法不指定文件路径会在程序当前路径生成文件, 但我使用Xcode时程序运行成功
* 但就是没有生成文件,加上路径就可以生成.
* 若output.txt已经存在,程序将新建一个空白的output.txt文件并将源文件覆盖.
*/
outFile.open("/Users/br/Documents/C:C++/IO/IO/output.txt");
if (outFile.fail()) {
cout << "outFile opening failed.";
exit(EXIT_FAILURE);
}
outFile << "青春的土壤中,只有记忆是潮湿的,我们不是植物,不能在这片土壤中生生不息。"
<< "很多人问我,青春的诀别是否意味着年迈的将近,其实青春它一直都在继续。";
inFile.close();
outFile.close();
}
getChar.cpp
/*
* Please input the input file name
* /Users/br/Documents/C:C++/IO/IO/output.txt
* Here are the entire contents of the input file
* 青春的土壤中,只有记忆是潮湿的,我们不是植物,不能在这片土壤中生生不息。
* 很多人问我,青春的诀别是否意味着年迈的将近,其实青春它一直都在继续。
* I am done with writing the contents of the file
*/
#include <iostream>
#include <fstream>
void getInputStream(std::ifstream& in_s);
int main() {
using std::cout;
using std::string;
using std::cin;
char c;
std::ifstream outFile;
getInputStream(outFile);
cout << "Here are the entire contents of the input file\n";
/* 使用 outFile >> s 读取文件时单词之间的空格不会被读取,可用 outFile.get(s) 代替。
* 使用 cout.put(c) 替换 cout << c 可实现同样功能。
* 使用 while (!outFile.eof()) 替换 while (outFile >> c) 可实现同样功能,
* 两者的区别为前者到达文件末尾是会返回true,后者无返回值。
* /
while (outFile >> c)
cout << c;
cout << "\n I am done with writing the contents of the file\n";
outFile.close();
return 0;
}
void getInputStream(std::ifstream& outFile) {
std::string outPut;
std::cout << "Please input the input file name\n";
std::cin >> outPut;
outFile.open(outPut);
if (outFile.fail()) {
std::cout << outPut << "opening fail.\n";
exit(EXIT_FAILURE);
}
}