#include
#include
int main(int argc, char *argv[])
{
FILE *from, *to;
char ch;
if(argc!=3) {
printf("Usage: copy \n");
exit(1);
}
/* open source file */
if((from = fopen(argv[1], "rb"))==NULL) {
printf("Cannot open source file.\n");
exit(1);
}
/* open destination file */
if((to = fopen(argv[2], "wb"))==NULL) {
printf("Cannot open destination file.\n");
exit(1);
}
/* copy the file */
while(!feof(from)) {
ch = fgetc(from);
if(ferror(from)) {
printf("Error reading source file.\n");
exit(1);
}
if(!feof(from)) fputc(ch, to);
if(ferror(to)) {
printf("Error writing destination file.\n");
exit(1);
}
}
if(fclose(from)==EOF) {
printf("Error closing source file.\n");
exit(1);
}
if(fclose(to)==EOF) {
printf("Error closing destination file.\n");
exit(1);
}
return 0;
}
lähde: http://www.java2s.com/Code/C/File/Copyafile.htm
Tämä esimerkki ei toimi...? MIten tuota käytetään tai mitä tuohon pitää lisätä/muuttaa jotta se toimisi?
#include
int main(int argc, char *argv[])
{
FILE *from, *to;
char ch;
if(argc!=3) {
printf("Usage: copy \n");
exit(1);
}
/* open source file */
if((from = fopen(argv[1], "rb"))==NULL) {
printf("Cannot open source file.\n");
exit(1);
}
/* open destination file */
if((to = fopen(argv[2], "wb"))==NULL) {
printf("Cannot open destination file.\n");
exit(1);
}
/* copy the file */
while(!feof(from)) {
ch = fgetc(from);
if(ferror(from)) {
printf("Error reading source file.\n");
exit(1);
}
if(!feof(from)) fputc(ch, to);
if(ferror(to)) {
printf("Error writing destination file.\n");
exit(1);
}
}
if(fclose(from)==EOF) {
printf("Error closing source file.\n");
exit(1);
}
if(fclose(to)==EOF) {
printf("Error closing destination file.\n");
exit(1);
}
return 0;
}
lähde: http://www.java2s.com/Code/C/File/Copyafile.htm
Tämä esimerkki ei toimi...? MIten tuota käytetään tai mitä tuohon pitää lisätä/muuttaa jotta se toimisi?
Vastaukset 4
Vanhimmat
Tällaisen sain toimimaan
#include
#include
//#include
int main(void)
{
FILE *fs,*ft;
char ch;
//int arg=3;
char from[]="C:\\Downloads\\kokeilu.txt";
char to[]="E:\\kokeiluUsb.txt";
//arr[1]=from;
//arr[2]=to;
/*if(arg!=3)
{
printf("Argument Missing ! Press key to exit.");
getch();
//exit(1);
}*/
fs = fopen(from,"r");
if(fs==NULL)
{
printf("Cannot open source file ! Press key to exit.");
getch();
//exit(1);
}
ft = fopen(to,"w");
if(ft==NULL)
{
printf("Cannot copy file ! Press key to exit.");
fclose(fs);
getch();
//exit(1);
}
while(1)
{
ch = getc(fs);
if(ch==EOF)
{
break;
}
else
putc(ch,ft);
}
printf("File copied succesfully!");
fclose(fs);
fclose(ft);
return 0;
}
Mitä tämä meinaa tuossa 1. esimerkissä että nuo int arg ja char *argv[] ovat parametreinä main-ohjelmassa?
parametrejä:
argc parametrien lukumäärä
argv parametrit c-stringeinä
main function pitäisi aina olla esimerkin 1 mukainen.
Sen lisäksi jotkin kääntäjät/ympäristöt tukevat kolmen parametrin muotoa (kolmas sisältää ympäristömuutujat)
Tuota noin... miksi koulussa sitten aina on vain int main(void)
Ja onko tuo *argv osoitin?