A C program \"testMe.c\" is compiled to produce the binary \"testMe\". The main
ID: 3852746 • Letter: A
Question
A C program "testMe.c" is compiled to produce the binary "testMe". The main function starts with: int main(int argc, char **argv) and the program reads its arguments and prints them. (a) If it is called with: /testMe -f myfile.txt What will it print for its arguments (list your answer as argv[0] will be printed as...argv[1] will be printed as... etc.) (b) If instead it is called with: /testMe "-f myfile.txt" > temp What will it print for its arguments (list your answer as argv[0] will be printed as...argv[l] will be printed as... etc.). Explain. (c) Write a simple C program that will, when called with /testMeExplanation / Answer
(a) argv[0] will be printed as ./testMe , argv[1] will be printed as -f , argv[2] will be printed as myfile.txt
(b) argv[0] will be printed as ./testMe , argv[1] will be printed as -f myfile.txt , argv[2] will be printed as > , argv[3] will be printed as temp
Explanation : Command line arguments takes blank space as delimiter, hence the " - f myfile.txt" will be taken as a single argument as it is enclosed with in double quotes ( " ")
(c )
#include <stdio.h>
#include <stdlib.h>
int main( int argc, char *argv[] ) {
FILE *fp;
char* file_name;
char ch;
if(argv[2] != NULL)
{
file_name = argv[2];
}
else
{
perror("File doesn't exist ");
}
fp = fopen(file_name,"r");
if( fp == NULL )
{
perror("Error while opening the file ");
exit(EXIT_FAILURE);
}
while( ( ch = fgetc(fp) ) != EOF )
printf("%c",ch);
fclose(fp);
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.