c++文件的输入和输出(一)
1.向文件中输入内容

#include<iostream> #include<fstream> using namespace std; int main() { ofstream output; output.open("c:/scores.txt"); output<<"John 1991-01-01 100"<<endl; return 0; }

#include<iostream> #include<fstream> using namespace std; int main() { ofstream output; output.open("c:/scores.txt"); output<<"John"<<" "<<"1991-01-01"<<" "<<100; output<<"Smith"<<" "<<"1991-01-01"<<" "<<100; return 0; }
2.从文件中输出内容

#include<iostream> #include<fstream> using namespace std; int main() { ifstream input; input.open("c:/scores.txt"); char name[40],birthday[40]; int score; if(input.fail()) //判断文件是否存在 { cout<<"Don't exit the file"<<endl; cout<<"Exit the program"<<endl; return 0; } input>>name>>birthday>>score; cout<<name<<" "<<birthday<<" "<<score<<endl; return 0; }
3.检查文件是否结束

#include<iostream> #include<fstream> using namespace std; int main() { ifstream input; input.open("c:/scores.txt"); char name[40],birthday[40]; int score; if(input.fail()) //判断文件是否存在 { cout<<"Don't exit the file"<<endl; cout<<"Exit the program"<<endl; return 0; } input>>name>>birthday>>score; cout<<name<<" "<<birthday<<" "<<score<<endl; return 0; }
对于1中的两个数据3中有不同的运行结果,是应为endl的问题
当文件没有可以继续读入的内容时,eof()会返回true,程序是有操作系统来知道是否还有可读的数据。在UNIX系统中则是Ctrl+D
Windows系统中则是Ctrl+Z.
4.格式化输出

#include<iostream> #include<iomanip> #include<fstream> using namespace std; int main() { ofstream output; output.open("C:/format.txt"); output<<setw(6)<<"John"<<setw(2)<<"T"<<setw(6)<<"Smith"<<" "<<setw(4)<<90<<endl; return 0; }
按间隔符分离数据并进行读操作
使用流提取运算符(>>)读取数据时存在一个问题,其算法认为所有数据都是以空格符来分隔的,其引入的问题是如果字符串本身含有空格该怎么办??
getline函数读取包括空白字符的字符串
getline(char array[],int size,char delimitChar)
array[]:数组(待输出的数据)
size:待输出字符串的长度
delimitChar:间隔符(如果不写,默认是'\n',即整行的输出)
当函数独到间隔符或到达文件末尾,或者已经读到size-1个字符时,就会停止读取。数组中最后一个位置放置空结束符('\0').如果函数式在读到间隔符后终止,间隔符虽然被读入,但不保存在数组中。第三个参数delimitChar的默认值是('\n').

#include<iostream> #include<fstream> using namespace std; int main() { ifstream input; input.open("c:/score.txt"); char content[50]; while(!input.eof()) { input.getline(content,40); cout<<content<<endl; } input.close(); return 0; }
5.get:从一个输入对象读取一个字符
get 的三种表达形式
char get(); //Returns a char
istream *get(char &ch); //Read a character to ch
char get(char array[],int size,char delimiterChar); //Read into array
put:将指定的字符写入输入对象
void put(char ch)

#include<iostream> #include<fstream> using namespace std; int main() { const int FILENAME_SIZE=40; cout<<"Enter a source file name:"; char inputFilename[FILENAME_SIZE]; cin>>inputFilename; cout<<"Enter a target file name:"; char outputFilename[FILENAME_SIZE]; cin>>outputFilename; ifstream input; //原文件 ofstream output; //目标文件 input.open(inputFilename); output.open(outputFilename); while(!input.eof()){ output.put(input.get()); //input.get():从原文件中读一个字符 //output.put():向目标文件中写一个字符 } input.close(); output.close(); return 0; }