Linux平台下提供了标准的C库API实现对文件的读写操作,同样C++也提供了自身对文件流操作的一些手段.虽然不知道以后会不会用到,但是了解一下是很有必要的.
源码:
#include <iostream>
#include <fstream>
using namespace std;
int main(void)
{ char filename1[256],filename2[256];
cout<<"Input source file name: ";
cin>>filename1;
cout<<"Input destination file name: ";
cin>>filename2;
ifstream infile(filename1);
ofstream outfile(filename2);
char ch;
while(infile.get(ch))
outfile.put(ch);
infile.close();
outfile.close();
return 0;
}
C++中要实现对文件流的操作,需要包含头文件"include <fstream>".本程序需要把一个文件里面的内容复制到另外一个文件,比如我们有一个已经存在的文件叫source.txt,里面有如下内容:
Hello,SE7EN:
Remember,hope is a good thing!
编译运行:
root@se7en-LIFEBOOK-LH531:~/learn/Cpp_Program# g++ file.cpp -o file
root@se7en-LIFEBOOK-LH531:~/learn/Cpp_Program# ./file
Input source file name: source.txt
Input destination file name: dest.txt
root@se7en-LIFEBOOK-LH531:~/learn/Cpp_Program# cat dest.txt
Hello,SE7EN:
Remember,hope is a good thing!
root@se7en-LIFEBOOK-LH531:~/learn/Cpp_Program#