Hello all,
I have this assignement where I must write a simple copy file program passing the source file name as a ccommand line arguments. This is my first time working with command line argument so please bear with me.
When calling the program, I am passing the source file name as a parameter called "source.txt" which is in the same directory as the program executable. Here is the code;
Code:
/*------------------------------------------------------------------------------------------*/
/* Modify the following code; take the file name as command line argument and /* copy.
/*-------------------------------------------------------------------------------------------*/
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <string.h>
int main(int argc, char *argv[]){
char fileName[20];
FILE *source,*target;
char string[80];
printf(" This is a File Copy program.\n");
printf(" It copies the contents of this file to a file named copied.txt\n");
printf(" take the input file name as command line arguments \n");
printf(" Note: Source file should be stored in the same directory as \n");
printf(" the executable of this program.\n\n");
if (argc>1) {
source = fopen(argv[1],"r");
if (source == NULL)
printf(" Cannot open file, Now exiting......");
else
printf("\n Successful in opening file \n");
}
getche();
target = fopen("copied.txt","w");
if (target == NULL)
printf(" Cannot open target file copied.txt . Now exiting ....\n");
else
printf(" Target file 'copied.txt' opened.\n");
getche();
fclose(source);
/* Copy the file */
while(fgets(string,79,source)!=NULL)
fputs(string,target);
fclose(source);
fclose(target);
puts(" File Copied.");
getche();
}
My problem is this; when I try to read from the file and write to the target file right about here;
Code:
while(fgets(string,79,source)!=NULL)
fputs(string,target);
the while (fgets...) does not work at all (exits from the loops immediately) which leads me to believe that perhaps my source file is not open at all. But after my fopen above source is not equal NULL and the "Successfull" message prints.
Now obviously I am doing something wrong. I would like to know if there is there a better way to validate wether my source file is really opened?
Can anyone point me in the right direction? I have been reading a lot of posts on the subject and even though they did help and I believe I understand the basic principles, I am still not sure I am doing this the right way.
Thanks in advance,