||
一段时间不写代码,就会忘记怎么读文件、写文件。所以以代码加注释的形式总结一下最基本的。
#include <iostream>
#include <vector>
#include <fstream>
#include <sstream>
#include <iostream>
#include <cstdlib>
#include <cstdio>
using namespace std;
int main(int argc, const char ** argv)
{
if(argc!=3)
{
cout<<"Usage: "<<argv[0]<<"[input.file.name][output.file.name]"<<endl;
return 1;
}
//逐词读入文件
ifstream infi(argv[1]);
if(!infi)
{
cout<<"error: unable to open input file" <<argv[1]<<endl;
return -1;
//exit(EXIT_FAILURE); //这个也是异常退出,使整个程序结束
}
string one_line,one_word;
while(getline(infi,one_line))
{
if(one_line.length() == 0)//判断读入是否是空行
continue;
stringstream sstr(one_line.c_str());
sstr>>one_word;
one_word = one_word.substr(0,one_word.length()-1);
one_person.push_back(one_word);
while(sstr>>one_word)
{
one_person.push_back(one_word);
}
}
//读完,写完以后要关上
infi.close();
infi.clear();
}
//如果不是在main函数中直接读,那么read_file函数格式如下:
bool read_file(const char * input_file)
{
}
main函数中这样调用:read_file(argv[1]);
//输入输出重定向
freopen("a.txt","r",stdin);//每次用读入时都是从a.txt中读
freopen("b.txt","w",stdout);//每次用输出时都是写到b.txt中
//如果代码中没有写上面两句话,还 可以在运行程序时实现输入输出重定向:
./program <in.txt >out.txt
//写文件
ofstream outfi(argv[2]);
outfi<<"要写的内容";
outfi.close();
outfi.clear();
Archiver|手机版|科学网 ( 京ICP备07017567号-12 )
GMT+8, 2024-7-18 03:32
Powered by ScienceNet.cn
Copyright © 2007- 中国科学报社