Jump to content

How can i copy content from a file to another?

- - - - -

This topic has been archived. This means that you cannot reply to this topic.
3 replies to this topic

#1
Moudi

Moudi

    Programmer

  • Members
  • PipPipPipPip
  • 167 posts
I need to copy the text from 1.txt to 2.txt without erasing the content of 2.txt
Now i came out with this simple code.

#include<stdio.h>

int main(void)

{

	FILE *file, *file2;

	file=fopen("1.txt", "rb");

	file2=fopen("2.txt", "wb");

	char c;

    while ((c=fgetc(file))!=EOF)

    {

        fputc(c, file2);

    }

fclose(file);

fclose(file2);

}
But its erasing the original content of 2.txt, i want it to keep it and write + it.
Is there some sort of way to make the loop begin from the EOF ?

#2
Xility

Xility

    Programmer

  • Members
  • PipPipPipPip
  • 130 posts
Hi,

If you want to append the content from 1.txt to 2.txt, then you should set the mode of the second fopen to "ab" instead of "wb".

file2=fopen("2.txt", "ab");

For more information about the different modes look here

Edited by Xility, 26 January 2010 - 05:51 AM.
For some reason the link messed up

Due to circumstances beyond my control I am master of my fate and captain of my soul.
— Ashleigh Brilliant

#3
Moudi

Moudi

    Programmer

  • Members
  • PipPipPipPip
  • 167 posts
Alright thanks ! it worked :)

#4
dcs

dcs

    Programming God

  • Members
  • PipPipPipPipPipPipPip
  • 775 posts

Moudi said:

	[COLOR="red"]char [/COLOR]c;

    while ((c=fgetc(file))!=EOF)
You should declare c as an int.
Cprogramming.com FAQ > Definition of EOF and how to use it effectively