Append File

Write here if you have problems with your C++ source code

Moderator: Board moderators

Post Reply
asyukri10
New poster
Posts: 5
Joined: Wed Nov 28, 2001 2:00 am
Location: Malaysia
Contact:

Post by asyukri10 »

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);

Wedson
New poster
Posts: 3
Joined: Sun Nov 25, 2001 2:00 am
Location: Brazil

Post by Wedson »

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";
}

Post Reply

Return to “C++”