Jump to content

Renaming In C++


Recommended Posts

Hello,

I have this problem. I tried to rename a file, it would success if I do it in the way where

char mychar[]= "file.txt";

However, I tried using from string, and converting that string to char, the compiler says that it is impossible to convert that string to a char. So I was wondering if is there any other solutions or can I actually really convert string to char?

Anyhow, here is my idea:

I am actually building this program to allow users to rename the file to something, which means they have to tell me (the program) the path to that folder. And I will rename that folder to a new name.

Here is my code:

#include <iostream>

#include <stdlib.h>

#include <string>

#include <stdio.h>

using namespace std;

int main(int argc, char *argv[])

{

string test;

cout << "Please insert Folder path" << endl;

cout << "Path: ";

getline (cin, test);

cout << test << endl;

char mychar[] = test;

char mychar2[] = test + "2"; // which will rename the folder to folder2

int result = rename(mychar, mychar2);

if(result != 0)

cout << "An Error Have Occured!" << endl;

else

cout << "Rename Successful!" << endl;

system("PAUSE");

return 0;

}

Edited by Zepx
Link to comment
Share on other sites


To convert a std::string to an const char* (which most C-functions need) you have to use the c_str() member function.

string s0 = "testfile";
string s1 = "testfile2";
rename(s0.c_str(), s1.c_str());

keep it up.

Link to comment
Share on other sites

  • 2 weeks later...

well, that depends on what you want to do exactly. when you do

cout << "Please insert Folder path\n";

you are adding that string to the screen buffer and not actually writing it to the screen. It won't be written to the screen until either the buffer is filled or flushed. on the other hand

cout << "Please insert Folder path" << endl;

the endl has an automatic flush buffer built into it so as soon as it's sent into the buffer, the buffer is flushed and the text appears on the screen. so basically, "\n" will write it to the buffer with a new line but not put it onto the screen until either the program exits or the buffer is flushed while endl adds the new line as well as flush the buffer and immediatly place the text on the screen.

Edited by cyprod
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...