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);
}
}