?? 11-8.txt
字號:
/* 范例:11-8 */
#include <fstream.h>
void main()
{
fstream io_file; // #1.1 只定義變量
char ch;
int start_pos=0; // 開始寫入字符串位置
int count=0;
io_file.open("out.txt",ios_base::in|ios_base::out); // #1.2
if(io_file.fail()) // #2 打開文件失敗時,fail()==true
{
cerr << "文件打開失敗!\nPress any key to Exit...";
getchar();
exit(1);
}
if((io_file.peek())==EOF) // #3 無文件的文件(僅EOF字符)
{
cerr << "文件內無文件!\n";
}
else
{
cout << "文件內源文件如下\n====================\n";
cout << io_file.rdbuf(); // 輸出 rdbuf()
count = io_file.tellg(); // #4 取得目前位置
cout << "\n====================\n";
cout << "共 " << count << " 字符\n";
cout << "您要從哪個位置插入字符串?(1-" << count+1 << ")";
cin >> start_pos;
start_pos--; // 由0開始,因此輸入值減一
if((start_pos <= count) && (start_pos >=0))
io_file.seekp(start_pos); // #5 移到指定位置
else
io_file.seekp(0);
while(cin.get() != '\n') // 清字符(含'\n')
{
}
}
cout << "輸入字符串,此字符串會被插入指定位置"
<< "(覆蓋,不清除源文件!)\n";
while((ch=cin.get()) != '\n') // 輸入非'\n'字符,則寫入io_file
{
io_file << ch;
}
io_file.seekg(0); // #6 字符指針指到頭(0)
cout << "全部字符串為:\n" << io_file.rdbuf() << "\n";
count = io_file.tellg(); // 取得總字數
cout << "請輸入要輸出最后幾個字符?(1-" << count << ") ";
cin >> start_pos;
// 輸入合理值時,倒退指定格數輸出
if((start_pos>=0)||(start_pos<=count))
{
io_file.seekg(count-start_pos);
cerr << io_file.rdbuf();
}
io_file.close();
getchar();
}
?? 快捷鍵說明
復制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -