Question: hi again, just wondering if anyone could check my code before I hand it in? thanks the questions are: 1. Write a program that: takes
hi again, just wondering if anyone could check my code before I hand it in? thanks
the questions are:
1. Write a program that: takes a file name from the command line; opens that file if possible; prints a message confirming that the file has been opened successfully; and closes the file. Note that your program should print an error message in the event that the file cannot be opened successfully. 2. Write a program that expands on the previous question by displaying all of the lines in the file to the screen before closing it. Your program should then output the number of lines in the file. You can make a reasonable assumption about the maximum size of a single line in the text file.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Q1:
#include
int main(int argc, char *argv[]){
FILE * fp;
fp = fopen(argv[1], "r");
if(fp != NULL){
printf("File Opened Successfully");
}
else{
printf("File Opened UnSuccessfully");
}
fclose(fp);
getch();
}
Q2:
#include
int main(int argc, char *argv[]){
FILE * fp;
fp = fopen(argv[1], "r");
int countLines = 0;
if(fp != NULL){
printf("File Opened Successfully ");
char line [ 128 ];
while ( fgets ( line, sizeof line, fp ) != NULL )
{
fputs ( line, stdout );
countLines++;
}
printf(" Number of Lines : %d",countLines);
}
else{
printf("File Opened UnSuccessfully");
}
fclose(fp);
getch();
}
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
