Files Class Activity
Write a program to write your first name (hardcoded) to the screen and possibly to a file whose name is passed into the program from the command line. It can be written in any case.
Usage: writer [-f filename]
• If the -f option is included with a filename, then create a file with that name or overwrite a previously existing file and write your name in the first line.
• If the -f option is not included, then only write your name to the screen followed by a newline.
Use a copy of the original getopt to parse the command line.
Solution:
#include < stdio.h>
#include < getopt.h>
int main(int argc, char ** argv) {
FILE *f;
char* name = "Manny";
printf("%s\n", name);
int opt;
while((opt = getopt(argc, argv, "f:")) != -1) {
switch(opt)
{
case 'f':
f = fopen(optarg, "w");
if (!f) {
printf("Can not open file %s\n", optarg);
return 0;
}
fprintf(f, "%s\n", name);
fclose(f);
break;
}
}
return 0;
}