Hi,
Does somebody know how to append a string to a file? I've tried as below but I think there are better solutions. Help me plz...
FILE* file;
char s[100];
if ((file=fopen("file.txt","r+"))==NULL)
{ printf("error!");
exit(1);
}
while(fgets(s,100,file));
fprintf(file,"my text!n");
fclose(file);
Append File
Moderator: Board moderators
In C++, files are represented using streams, so you should use file streams instead of those C-like FILE structs (although FILE structs are also part of C++). Here's a way of doing this in C++:
#include <fstream>
int main() {
ofstream f("test.txt", ios::app);
if (f) {
f << "New linen";
f.close();
} else cerr << "File could not be opened.n";
}
#include <fstream>
int main() {
ofstream f("test.txt", ios::app);
if (f) {
f << "New linen";
f.close();
} else cerr << "File could not be opened.n";
}