Writing a program that reads a given file character by character, and prints them on the screen, followed by the number of lines and characters. The name of the file will be read from the command line, as follows:
ProgramName filename
You are supposed to use the skeleton file ReadFile.c
After adding the missing codes, execute your program with the text file failure_to_communicate.txt given as the command line argument. Does your program print all the contents of the file? Are the values displayed for number of lines and characters correct? If not, correct the code appropriately so that your program prints all of the file contents, and the values displayed for number of lines and characters are correct.
Test: You can test your code by checking if the contents of the failure_to_communicate.txt are properly displayed attached bellow, followed by the number of lines and characters, which are 9 and 594, respectively.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 |
#include <stdio.h> #include <stdlib.h> int main(int argc, const char * argv[]) { const char *fileName; FILE *fp1; int numLines = 0; int numChars = 0; int numChars1 = 0; int numChars2 = 0; // Your code starts here int myvariable; if (argc != 2) { printf ("Filename is not given please try again"); return 0; } fileName = argv [1]; fp1 = fopen(fileName,"r"); if (fp1 != NULL) { char c; while ((c=fgetc(fp1))!=EOF) { putchar(c); ++numChars; if (c != '\n') { ++numChars1; } if (c != ' ' && c != '\n') { ++numChars2; } if (c == '\n') { ++numLines; } } if (numChars > 0) { ++numLines; } int count; printf ("\n------------------\n"); printf("\nNumber of lines:%d\nNumber of characters:%d\nNumber of characters(without enter):%d\nNumber of characters(without enter and space):%d\n", numLines, numChars, numChars1, numChars2); fclose(fp1); } else { printf("File: %s could not be opened\n", fileName); } return EXIT_SUCCESS; } |