how to use command argument?
there is an error in fopen.c how can i solve it? error in assigning argv[1], argv[2] to ft, fs.
int main ( int argc, char *argv[] )
{
//FILE *fs, *ft ;
char ch ;
//ft = fopen ("d:\\out.txt", "w") ;
fs = fopen( arg开发者_如何转开发v[1], "r" );
if ( fs == NULL ) {
puts ( "Cannot open source file" ) ;
exit(1) ;
}
//fs = fopen("d:\in_file.txt","r") ;
ft = fopen( argv[2], "w" );
if ( ft == NULL ){
puts ( "Cannot open target file") ;
exit(1) ;
}
}
At first, there a huge indentation problem in your code. Please solve it. [EDIT: Now it is ok]
Second, what kind of error? Both fs and ft are equal to NULL? Instead of using puts to display error message, you can use perror(const char *s). This will add informations to your message knowing the stat of the errno variable.
This works for me. It's a program that copies vowels and linefeeds ('\n') from the file specified in the 1st argument to the file in the 2nd argument.
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char **argv) {
FILE *fi, *fo;
if (argc != 3) {
fprintf(stderr, "syntax: %s in out\n", argv[0][0]?argv[0]:"program");
fprintf(stderr, "copies vowels and linefeeds from in to out\n");
exit(EXIT_FAILURE);
}
fi = fopen(argv[1], "r");
if (!fi) {
perror("input file");
exit(EXIT_FAILURE);
} else {
fo = fopen(argv[2], "w");
if (!fo) {
perror("output file");
exit(EXIT_FAILURE);
} else {
int ch;
while ((ch = fgetc(fi)) != EOF) {
switch (ch) {
case 'a': case 'e': case 'i':
case 'o': case 'u': case '\n':
fputc(ch, fo);
break;
default:
break; /* do nothing */
}
}
fclose(fo);
}
fclose(fi);
}
return 0;
}
When I run it with the source above as input (./a.out 5292243.c 5292243.vowels
), the resulting file contains
iueio iuei iaiiaaa io ia ieaiouaaoa ieoieoeaieeeoioou ei ioea ii eoiuie ei ee ooea io eoouuie ei ee i ieei i aeaaeeaei aeoaeuaeuo eaueaooi oeo oei eu
精彩评论