Reputation: 3
This is what my professor provided me in his own words.
"Write a program that copies the contents of a text file specified by the user and copies it to another text file "copy.txt". No line in the file is expected to be longer than 256 characters."
Here is the code I devised so far with his info:
#include <stdio.h>
#include <io.h>
#include <stdlib.h>
#include <conio.h>
#include <string.h>
int main ( void )
{
char filename[256]=""; //Storing File Path/Name of Image to Display
static const char file2name[] = "C:\\Users\\Rael Jason\\Desktop\\Rael's iPod\\Codeblocks\\copy.txt";
FILE *file;
FILE *write;
printf("Please enter the full path of the text file you want to copy text: ");
scanf("%s",&filename);
file = fopen ( filename, "r" );
file = fopen (file2name, "r" );
if ( file != NULL )
{
char line [ 256 ]; /* or other suitable maximum line size */
char linec [256]; // copy of line
while ( fgets ( line, sizeof line, file ) != NULL ) /* read a line */
{
fputs ( line, stdout ); /* write the line */
strcpy(linec, line);
fprintf (write , linec);
fprintf (write , "\n");
}
fclose (write);
fclose ( file );
}
else
{
perror ( filename ); /* why didn't the file open? */
}
return 0;
}
I just can't seem to get the file writing done right? Can you please help?
Upvotes: 0
Views: 18763
Reputation: 229
If this is the code you executed then there are some problem with it.
FILE
pointer file to open both the source and destination file.Upvotes: 1
Reputation: 26
You had the copy and paste issue as mentioned by stacker. And there no need to add an extra newline character. Try the following code.
#include <stdio.h>
#include <io.h>
#include <stdlib.h>
#include <conio.h>
#include <string.h>
int main ( void )
{
char filename[256]=""; //Storing File Path/Name of Image to Display
static const char file2name[] = "C:\\Users\\Rael Jason\\Desktop\\Rael's iPod\\Codeblocks\\copy.txt"; Copy File
FILE *file;
FILE *write;
char line [ 256 ]; /* or other suitable maximum line size */
char linec [256]; // copy of line
printf("Please enter the full path of the text file you want to copy text: ");
scanf("%s",&filename); // Enter source file
file = fopen ( filename, "r" );
write = fopen (file2name, "w" );
if ( file != NULL )
{
while ( fgets ( line, sizeof line, file ) != NULL ) /* read a line */
{
fputs ( line, stdout ); /* write the line */
strcpy(linec, line);
fprintf (write , linec);
// fprintf (write , "\n"); // No need to give \n
}
fclose (write);
fclose ( file );
}
else
{
perror ( filename ); /* why didn't the file open? */
}
return 0;
}
Upvotes: 1