c++ - Changing last 5 char of array -
i have program encrypts files, adds extension ".safe" end. end result "file.txt.safe"
when go decrypt file, user enters file name again: "file.txt.safe" saved char. want remove ".safe" , rename file original name.
i have tried following, nothing seems happen , there no errors.
decrypt (myfile); //decrypts myfile char * tmp = myfile; char * newfile; newfile = strstr (tmp,".safe"); //search tmp ".safe" strncpy (newfile,"",5); //replace .safe "" rename (myfile, newfile); i'm sure i'm missing obvious, if approach doesn't work, i'm looking simple method.
edited add: (copied moderator poster's response k-ballo)
thanks everyone. took std::string approach , found work:
decrypt(myfile); string str = myfile; size_t pos = str.find(".safe"); str.replace(pos,5,""); rename(myfile, str.c_str());
for want do, changing strncpy line work:
*newfile = '\0'; this still have problems if filename contains .safe (like in file.safest.txt.safe), or if not contain substring .safe @ all. better of searching end of array, , making sure find something.
this seems better approach (although in c++ better go std::string):
char* filename = ...; size_t filename_length = strlen( filename ); int safe_ext_pos = filename_length - 5; // 5 == length of ".safe" if( safe_ext_pos > 0 && strcmp( ".safe", filename + safe_ext_pos ) == 0 ) filename[ safe_ext_pos ] = '\0'; this std::string version of code:
std::string filename = ...; int safe_ext_pos = filename.length() - 5; // 5 == length of ".safe" if( safe_ext_pos > 0 && filename.compare( safe_ext_pos, 5, ".safe" ) == 0 ) filename.erase( safe_ext_pos );
Comments
Post a Comment