Well the program below is absolutely useless. When I execute it I create a file with the name of the address and not with the name "file.txt".In addition when I try to delete it nothing happens. What I want it to do is to create a file called file.txt and then delete it. I understand that the file is called with the address and not file.txt because I use the address pointer but I have no clue how to fix it.
#include <iostream>
#include <fstream>
#include "stdlib.h"
usingnamespace std;
int main(){
void save(string fname, int x);
void del(string fname);
const string fname = "file.txt";
int x = 312;
save(fname, x);
del(fname);
}
void save(string fname, int x){
std::ofstream fout(fname);
fout<<std::endl<<x<<std::endl;
}
void del(string fname){
remove(fname); //No matching function for call to "remove"
}
And I get 2 errors:
1)No matching function for call to "remove"
2)Undefined symbols for architecture x86_64:
"del(std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >)", referenced from:
_main in main.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
I should build a church for you. Thank you, now it works fine. Just for the glory of the high heavens, I tried to run it without this line (I commented it) #include <cstdio>
and it worked fine too. I guess that happened because I had the "stdlib.h" included but I understand that it would be a "good practise" to include the <cstdio>. One more thing. Can you explain me the difference between the 2 type of strings (the so called c-string and the std::string)?
Regarding the #include . Often one header may include some or all of another header, so it may not be necessary to explicitly state all the required headers. It depends on which compiler you use, code which works in one may not work in another. If you put all the required includes, the code will be more portable, that is it should work on any compiler which conforms to the standard.
As for the different string types. C++ is originally based upon C (though the two languages have diverged somewhat). In C, a string is simply an array of characters. The end of such a string is marked by a null character, that is a byte with the numeric value zero.
You can read in detail about them in the tutorial here: http://www.cplusplus.com/doc/tutorial/ntcs/
That same tutorial page also mentions the C++ std::string. In C++ code this is preferred. It is generally safer and easier to use, it takes care of the low-level operations such as allocating and freeing storage, automatically resizing as required and so on.