I am trying to delete a .txt file. When hardcoding the .txt, like Banana.txt it functions like expected with the remove function. But when i am trying to use a string variable to choose which file i should remove it says it cant recognise remove.
1 2 3 4 5 6
void eraseUser() {
std::string username;
std::cout << "Which file do you want to erase? (Case sensitive)" << std::endl;
std::cin >> username;
std::remove(username + ".txt");
}
.c_str() returns a C style string, which is just an array of characters, which is how the C language (and C++ inherits this capacity) handles 'strings'.
@nico. That link doesn't work as it treats the final . as part of the link! You need to have at least one white-space before/after . Try https://en.cppreference.com/w/cpp/io/c/remove
delete is part of the C library - so doesn't know anything about std::string.
So it would be better to use the <filesystem> header and use remove from there? Because we are working in c++. And then i would not need to make the string to a char array?
When writing new C++ code using newer standard C++ constructs and libraries is a good idea.
Although also knowing the C library as well as older C++ standards is also a good thing because it makes understanding and maintaining older code that works less of a headache.
Updating older code to a newer standard is a great learning/intellectual exercise, just don't do it on production code unless the company wants it.
You are combining code snippets into a royal mess. That fscrap is from namespace fs = std::filesystem;, a way of reducing key-strokes. Did you notice I don't use it?
Just fully qualify the std::filesystem::remove function, as I did.
OR use the namespace qualifier and call the function as if (fs::filesystem::remove(username + ".txt"))
If that use of namespace confuses you DON'T USE IT.
It doesn't confuse me, though I still won't use it.
Trying to save a couple of keystrokes by all these namespace short-cuts can be a huge source of errors as you've discovered. I learnt this lesson the HARD WAY.
#include<iostream>
#include<fstream>
#include<stdio.h> // rename, remove
usingnamespace std;
int main()
{
char name[20],filename[20],newname[20];
/*create filename*/
cout<<"Enter file-name to create: ";
gets(filename);
ofstream fout(filename);
/*save record into file*/
cout<<"\nEnter a name to store in it: ";
gets(name);
fout<<name;
fout.close();
cout<<"\nrecord saved into file called - "<<filename<<endl;
/*rename file*/
cout<<"\nHit to Rename this file";
cout<<"\nEnter new name: ";
gets(newname);
rename(filename,newname);
cout<<"\nNow file name is: "<<newname<<endl;
/*remove file*/
cout<<"\nHit to remove file\n";
remove(newname);
cout<<"\nfile removed successfully...";
}
OUTPUT
1 2 3 4 5 6 7 8 9 10 11 12 13 14
Enter file-name to create: database
Enter a name to store in it: rahul
record saved into file called - database
HIT ENTER to Rename this file
Enter new name: file
Now file name is: file
HIT ENTER to Remove file
file removed successfully...