empidocl empidocl - 3 months ago 10
C++ Question

open file, save duplicate with different name

Hello c++ newbie over here !!!

I am working on a very simple program, that opens files saved into a vector, reverses the content text for each files, and saves the new file.
I am using code blocks

example:




  • open "test.txt"

  • reverse lines

  • creates "m_test.txt"

  • delete "test.txt"

  • do the same to other files in the vector.



I get an error in :
outFile.open( foundFiles[i].insert(3,"m_"), fstream::in);

" no matching function for call to 'std::basic_fstream::open(std::basic_string&, std::_Ios_Openmode)'| "

here is the code so far:



 string reverseLine(string message);

string reverseLine(string message)
{
string reversed;
int i = message.length() -1;
while (i>=0)
{
reversed = reversed + message[i];
i = i -1;
}
return reversed;
}


void filesToModify();

void filesToModify() // put files into vector
{

fstream filesInVector; // files open from the vector
string openFLine; // lines read from the files read from the vector

fstream outFile; //files saved after reversing the files

vector <string> foundFiles; //vector holding all the files to be reversed


foundFiles.push_back("e:/file_1.txt");
foundFiles.push_back("e:/file_2.txt");
foundFiles.push_back("e:/file_3.txt");

for (int i=0; i<foundFiles.size(); i++) // read the files inside the vector
{
filesInVector.open(foundFiles[i], fstream::in);

while (!filesInVector.eof())
{
getline(filesInVector,openFLine);
outFile<<reverseLine(openFLine);
outFile.open( foundFiles[i].insert(3,"m_"), fstream::in); // add "m_" to the created file
foundFiles[i].close(); // close the file

std::remove(foundFiles[i]); // remove the original file
}
}

int main()
{

filesToModify();

}

Answer
outFile.open( foundFiles[i].insert(3,"m_").c_str (),  fstream::in);

C++ used to have no string datatype. It was added later in the STL (standard template library. These early C++ versions used a char* (pointer to character). A string was simply represented by a character array, terminated by a 0 char (char with code 0). The pointer held the address of the first char of this array.

Some functions still expect a char* instead of a string. Method c_str () of STL class string converts an STL string to a char*.

Comments