Hi,
Today I decided to code a small program that could make a backup file.
I wanted to change the extension of the given file to "BAK" to be able
to make a backup file.
So I coded the below program but when I tried to use strcat(); function
to change the extension of the given file to a backup file I faced a problem
and I was not able to handle it.
Finally after pondering a lot,I changed my program and used a for loop
to be able to solve the problem.
You can see this loop in the second program which is below.
But it was not what i wanted to do.
I wanted to use strcat(); function and I hope someone can help me
to correct the first program.
Thanks in advance.
Best Regards,
Zest.
The imcomplete program:
Code:
#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
#include <string.h>
#define SIZE 40
int main(int argc,char * argv[])
{
FILE *in,*out;
char name[SIZE],chr = '.',bk[] = "Bak",ch;
char *occurance;
if(argc != 2)
{
puts("This program makes a BackUp of your files");
fprintf(stderr,"Usage: %s filename\n",argv[0]);
exit(EXIT_FAILURE);
}
if((in = fopen(argv[1],"r")) == NULL)
{
fprintf(stderr,"I can't open the file %s",argv[1]);
exit(EXIT_FAILURE);
}
strncpy(name,argv[1],SIZE-5);
name[SIZE-5] = '\0';
occurance = strchr(name,chr);
strcat(occurance , bk);
if((out = fopen(name, "w")) == NULL)
{
fprintf(stderr,"I can't copy to the file %s",name);
exit(EXIT_FAILURE);
}
//Copying Data
while((ch = getc(in))!= EOF)
putc(ch,out);
if(fclose(in) != 0 || fclose(out) != 0)
fprintf(stderr,"Error is closing files.\n");
puts("Done!\n");
getch();
return 0;
}
The program with for loop:
Code:
#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
#include <string.h>
#define SIZE 40
int main(int argc, char* argv[])
{
FILE *in,*out;
char name[SIZE],chr = '.',bk[] = ".Bak",ch;
char *occurance;
if(argc != 2)
{
puts("This program makes a BackUp of your files");
fprintf(stderr,"Usage: %s filename\n",argv[0]);
exit(EXIT_FAILURE);
}
if((in = fopen(argv[1],"r")) == NULL)
{
fprintf(stderr,"I can't open the file %s",argv[1]);
exit(EXIT_FAILURE);
}
strncpy(name,argv[1],SIZE-5);
name[SIZE-5] = '\0';
occurance = strchr(name,chr);
for(int i = 0; i < 4; i++)
*(occurance + i) = bk[i];
if((out = fopen(name, "w")) == NULL)
{
fprintf(stderr,"I can't copy to the file %s",name);
exit(EXIT_FAILURE);
}
//Copying Data
while((ch = getc(in))!= EOF)
putc(ch,out);
if(fclose(in) != 0 || fclose(out) != 0)
fprintf(stderr,"Error is closing files.\n");
puts("Done!\n");
getch();
return 0;
}