Mega Code Archive

 
Categories / C++ / File
 

Demonstrate rename() and remove()

#include <iostream> #include <cstdio> #include <cstring> #include <fstream> using namespace std; int main(int argc, char *argv[]){   int result;   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; }