C++ examples for File Stream:File Operation
Demonstrate rename() and remove() on file
#include <iostream> #include <cstdio> #include <cstring> #include <fstream> using namespace std; int main(int argc, char *argv[]) { int result;/*from w w w.j av a 2 s . com*/ if(argc != 2) { printf("usage: EraseRenname <erase/rename>\n"); exit(1); } ofstream fout("test.dat"); if(!fout) { cout << "Cannot open test.dat file.\n"; return 1; } fout << "Write some data to the file."; fout.close(); if(!fout.good()) { cout << "Error writing to or closing file.\n"; return 0; } if(!strcmp("erase", argv[1])) { result = remove("test2.dat"); if(result) { cout << "Cannot remove file.\n"; return 1; } } else if(!strcmp("rename", argv[1])) { result = rename("test.dat", "test2.dat"); if(result) { cout << "Cannot rename file.\n"; return 1; } } else cout << "Invalid command-line argument.\n"; return 0; }