good day and a happy new year to you folks. im trying to copy the contents of one text file to another text file but i cant seem to get it right. written below is the code im using but it does not seem to work. any help please?

#include <stdio.h>
#include <conio.h>
#include <string.h>

int main (void){
    
    static const char filename[] = "file.txt";
    static const char file2name[] = "file2.txt";    
    FILE *read = fopen ( filename, "r" );
    FILE *write;
    
    char line [128];
    
    if ( read != NULL ){ 
         while ( fgets ( line, sizeof line, read ) != NULL ){
               write = fopen (file2name , "w");
               fprintf (write , line);
               fprintf (write , "\n");
               fclose (write);
               }
         fclose ( read );
         }
             
    else{
         perror ( filename ); /* why didn't the file open? */
      }
      
    getch();
    return 0;
}

Dani AI

Generated

A few concrete, reliable fixes to the problems shown in this thread:

  • Opening the output file inside the read loop will repeatedly truncate it and is inefficient. Open both files once, verify each fopen succeeded, then do the copy.
  • Never pass an input buffer directly as the fprintf format string (for example fprintf(out, line)). That lets percent-escapes in the data be interpreted and can crash or produce garbage. Use fputs(line, out) or fprintf(out, "%s", line) instead.
  • For formatted numbers (floats) prefer fprintf(out, "%f\n", value). If you format into a temporary string, write only the printed length (e.g. strlen(buf)), not the whole buffer, or you will write trailing garbage bytes.

A simple, safe text-copy pattern:

FILE *in = fopen("file.txt", "r");
FILE *out = fopen("file2.txt", "w");
if (!in || !out) { perror("fopen"); /* cleanup */ }
char line[1024];
while (fgets(line, sizeof line, in) != NULL) {
    if (fputs(line, out) == EOF) { perror("write"); break; }
}
fclose(out);
fclose(in);

For raw/binary copies use a block loop and check return values:

char buf[4096];
size_t n;
while ((n = fread(buf, 1, sizeof buf, in)) > 0) {
    if (fwrite(buf, 1, n, out) != n) { perror("write"); break; }
}

Notes and small tips: use "rb"/"wb" on Windows for binary files; BUFSIZ or 4096 is a good buffer size; check ferror/feof on failure; remove nonstandard conio.h/getch() if portability matters; seed rand() when generating random values. These changes address the truncation, format-string and trailing-junk issues discussed by and while keeping the code robust and portable.

Recommended Answers

All 4 Replies

Line 19...Why are you closing write here?

actually line 16...Why are you opening write here?

Try looking at the code below

#include <stdio.h>
#include <stdlib.h>

#define BSIZE 24

int main()
{
	char ch[BSIZE];
	FILE *fout;
	FILE *fin;

	if (!(fin = fopen("testfile", "r")))
	{
		fputs("could not open testfile!\n", stderr);
		exit(EXIT_FAILURE);
	}

	if (!(fout = fopen("testout", "w")))
	{
		fputs("could not open testout!\n", stderr);
		exit(EXIT_FAILURE);
	}

	while (fwrite(ch, sizeof(char), fread(ch, sizeof(char), BSIZE, fin), fout))
	{
	}

	fclose(fout);
	fclose(fin);
	return 0;
}

thank you so much for taking the time to reply to my post. it turns out that i have to perform checking with the opened file first, process that data and then print to another file. ive tried applying your suggestions but it seems i cant quite get the hang of it. i get a problem regarding floats, once i print them to the file they get trash values appended. something like "àÿ" ”\Ãwp Á "

written below is the code that generates random numbers and writes it to a text file (with the trash values).

#include <stdio.h>
#include <stdlib.h>
 
#define BSIZE 24

float rand_FloatRange(float a, float b);
 
int main()
{
	char ch[BSIZE];
	char out[BSIZE];
	char newl[] = "\n";
	float randf;
	FILE *fout;
	int times;
 
	if (!(fout = fopen("testout.txt", "w")))
	{
		fputs("could not open testout!\n", stderr);
		exit(EXIT_FAILURE);
	}
 
    for (times = 0; times < BSIZE; times++){
        randf = rand_FloatRange(0.0 , 1.0);
        sprintf (out , "%f" , randf);
        fwrite  (out, sizeof(char), sizeof(out), fout);
        fwrite  ("\n" , sizeof(char) , sizeof(char) , fout);
    }   
 
	fclose(fout);
	return 0;
}

float rand_FloatRange(float a, float b)
{
return ((b-a)*((float)rand()/RAND_MAX))+a;
}

Hello Happy New Year
the reason why you are getting junk is that size of out is 24 and in the

int fwrite( const void *buffer, size_t size, size_t count, FILE *stream );

you are inserting 24 in 2nd arg which should be 8 in your case.

As a result 16 bytes of out are printed in file after '\0' which are junk.

So you must use strlen() function to insert correct size.

Correct code is

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define BSIZE 24

float rand_FloatRange(float a, float b);

int main()
{
	char ch[BSIZE];
	char out[BSIZE];
	char newl[] = "\n";
	float randf;
	FILE *fout;
	int times;

	if (!(fout = fopen("testout.txt", "w")))
	{
		fputs("could not open testout!\n", stderr);
		exit(EXIT_FAILURE);
	}

    for (times = 0; times < BSIZE; times++){
        randf = rand_FloatRange(0.0 , 1.0);
        sprintf (out , "%f" , randf);
        fwrite  (out, strlen(out), 1, fout);
        fwrite  ("\n" , sizeof(char) , 1, fout);
    }

	fclose(fout);
	return 0;
}

float rand_FloatRange(float a, float b)
{
return ((b-a)*((float)rand()/RAND_MAX))+a;
}

Vinayak

happy new year to you too vinayak! thank you very much for replying and you are absolutely correct!

mr. gerard4143, thank you very much too!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.