text file statistics and problems displaying them - c

I am working on an assignment for class and we basically have to prompt a user to input two text files. The program should then read the files, display them, and also display the separate file statistics.
I have been working on the code and seem to have hit a brick wall. I can only seem to display the statistics for the second text file; moreover, the text from said file doesn't seem to be getting displayed.
Very confused indeed, so any help will be hugely appreciated. I am still really struggling with this class, despite my efforts. :(
Anyway, the code (a total mess I am sure):
#include <stdio.h>
int main() {
FILE *fp;
char ch;
int lineCount, wordCount, charCount;
char filename[50], filename2[50];
lineCount = 0;
wordCount = 0;
charCount = 0;
printf("Enter a filename: ");
gets(filename);
fp=fopen(filename, "r");
if(fp==NULL) {
printf("Error!\n");
return 1;
}
while((ch=fgetc(fp)) != EOF) {
putchar(ch);
}
fclose(fp);
printf("\n");
printf("Enter a second filename: ");
gets(filename2);
fp=fopen(filename2, "r");
if(fp==NULL) {
printf("Error!\n");
return 1;
}
while((ch=fgetc(fp)) != EOF) {
if ( fp )
{
while ((ch=getc(fp)) != EOF) {
if (ch != ' ' && ch != '\n') { ++charCount; }
if (ch == ' ' || ch == '\n') { ++wordCount; }
if (ch == '\n') { ++lineCount; }
}
if (charCount > 0) {
++lineCount;
++wordCount;
}
}
printf("Lines counted: %d \n", lineCount);
printf("Words counted: %d \n", wordCount);
printf("Characters counted: %d \n", charCount);
getchar();
putchar(ch);
}
fclose(fp);
printf("\n");
return 0;
}

Your first loop reads & displays the first file, not attempting to either collect or report any statistics; your second loop reads, collects & reports statistics, but does not attempt to display.
My suggestions would be to write a function to do all of this for a single file, and then call it once for each file you wish so processed.

Related

How do I make a program in C that will read ad print specific lines from a file?

#include <stdio.h>
#include <stdlib.h>
int main(void)
{
FILE * ofile;
char fname[100], c;
printf("Please enter a file name: \n");
scanf("%s", fname);
ofile = fopen(fname, "r+");
if (ofile == NULL)
{
printf("This file cannot be opened!\n");
exit(0);
}
c = fgetc(ofile);
while (c != EOF)
{
printf("%c", c);
c = fgetc(ofile);
}
fclose(ofile);
return 0;
}
This is what I have, and it just prints everything. I can't find any resources that tell me how to make it print just the first or last three lines, or how to specify lines at all. I don't need to specify by what the lines contain, just where they are.
You can manually track which line you are on and compare.
int line = 0;
while (c != EOF)
{
if (c == '\n')
{
line++;
}
if (line != 0)
{
printf("%c", c);
}
c = fgetc(ofile);
}
This addition will skip the first line, but print the rest. It can be modified as you like.

Line counting in C but exclude empty lines

I've got the following program, but there is a problem. First the program part that does not work:
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE *fp;
FILE *fp2;
char ch;
char fnamer[100];
char fnamer2[100]; //Storing File Path/Name of Image to Display
printf("\n\nPlease Enter the Full Path of the Image file you want to view: \n");
scanf("%s",&fnamer);
fp=fopen(fnamer,"r");
if(fp==NULL)
{
printf("Error!");
exit(1);
}
printf("\n\nPlease Enter the Full Path of the Image file you want to write to: \n");
scanf("%s",&fnamer2);
fp2=fopen(fnamer2,"w");
if(fp2==NULL)
{
printf("Error!");
exit(1);
}
else
{
// printf("test\n");
}
int line_number = 0;
int charsOnLine = 0;
fprintf(fp2, "%d: ", ++line_number); /* put line number in output file */
printf("%d: ", line_number);
while((ch = fgetc(fp)) != EOF )
{
//printf("test2");
fputc(ch,fp2);
printf("%c", ch);
if ( ch != '\n' && charsOnLine ==0 )
{
fprintf(fp2, "%d:", ++line_number ); /* put line number in output file */
printf("%d: ", line_number);
}
// if (ch != '\n' && charsOnLine 0 ){
// fprintf(fp2, "%c", ch);
// printf("%d", ch);
// }
}
fclose;
fclose(fp);
// fclose(fp2);
// getch();
}
The program needs to count the lines, give them a number but skip the blank lines. But here is the problem: when I run this code it gives all the chars a number.
You could use a flag to remember when you have just started a new line. The first time you see a char not equal to '\n', you print the line number and clear the flag.
Something like:
int line_number = 0;
int newLine = 1;
while((ch = fgetc(fp)) != EOF )
{
if (ch == '\n')
{
newLine = 1;
}
else
{
if (newLine)
{
fprintf(fp2, "%d:", ++line_number );
printf("%d: ", line_number);
newLine = 0;
}
}
fputc(ch,fp2);
printf("%c", ch);
}
From what I understand, the program needs to count the lines and append their content.
Then I would search for '\n' char, rather than skipping it with if (ch != '\n')
int main()
{
FILE *fp;
FILE *fp2;
char ch;
char fnamer[100];
char fnamer2[100]; //Storing File Path/Name of Image to Display
printf("\n\nPlease Enter the Full Path of the Image file you want to view: \n");
scanf("%s",&fnamer);
fp=fopen(fnamer,"r");
if(fp==NULL)
{
printf("Error!");
exit(1);
}
printf("\n\nPlease Enter the Full Path of the Image file you want to write to: \n");
scanf("%s",&fnamer2);
fp2=fopen(fnamer2,"w");
if(fp2==NULL)
{
printf("Error!");
exit(1);
}
int line_number = 0;
fprintf(fp2, "%d: ", ++line_number );
while((ch = fgetc(fp)) != EOF )
{
if ( ch == '\n' )
{
fprintf(fp2, "%d: ", ++line_number ); /* put line number in output file */
}
else {
fputc(ch,fp2); /* put the char in the corresponding line */
}
}
fclose(fp);
fclose(fp2);
}

A C program to read in two files and display their statistics on screen

I need to make a program that prompts the user for the name of two text files which will be read in and displayed on screen followed by their statistics, such as number of characters, words and lines. I've managed to get it all working apart from the statistics part. They don't seem to be counting up and I think it's something to do with the while statements that I've used. Any help would be great :)
code:
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
int main() {
// declaring variables
FILE *fp;
int charcount = 0, wordcount = 0, linecount = 0;
int character;
char first[50];
char second[50];
char ch[200];
// asking the user for the file names and scanning the names they enter as txt files
printf(" Enter the first file name: ");
scanf("%s", first);
strcat(first, ".txt");
printf(" Enter the second file name: ");
scanf("%s", second);
strcat(second, ".txt");
// opening the file stream
fp = fopen(first, "r");
// if the file cannot be reached, display error
if (fp == NULL) {
printf("File cannot be opened: %s\n", first);
return 0;
}
// reading and printing the file into the program
printf("\n---FIRST FILE---\n");
while (!feof(fp)) {
fgets(ch, 200, fp);
puts(ch);
}
// counting the characters, words and lines until the program is finished
while ((character = getc(fp)) != EOF) {
if (character == '-')
{
charcount++;
}
if (character == ' ')
{
wordcount++;
}
if (character == '\n')
{
linecount++;
}
}
// closing the stream
fclose(fp);
// printing the number of characters, words and lines
printf("\n Characters: %d \n Words: %d\n Lines: %d\n\n\n", charcount, wordcount, linecount);
//---------SECOND FILE----------//
// opening the stream
fp = fopen(second, "r");
// reading and printing the file into the program
printf("\n---SECOND FILE---\n");
while (!feof(fp)) {
fgets(ch, 200, fp);
puts(ch);
}
// counting the characters, words and lines until the program is finished
while ((character = getc(fp)) != EOF) {
if (character == '-')
{
charcount++;
}
if (character == ' ')
{
wordcount++;
}
if (character == '\n')
{
linecount++;
}
}
// closing the stream
fclose(fp);
// printing the number of characters, words and lines
printf("\n Characters: %d \n Words: %d\n Lines: %d\n\n", charcount, wordcount, linecount);
}
Imagine that you're using one of those text editors to open your file and moving the caret/cursor is the only way to navigate. Your first goal is to navigate through the whole content and display it. That's what the loop below does:
while(!feof(fp)){
fgets(ch, 200, fp);
puts(ch);
}
The !feof(fp) moved the cursor to the end of the file so you could read it all.
If you have to count chars then you need to navigate back to somewhere in your file. Since you want statistics from the whole txt, then you could simply use rewind(fp) or fseek(fp, 0, SEEK_SET) before your second loop to move the cursor back to the begin.
I recommed using fseek() because it will clear the end of file indicator.
Take a closer look here.
I finally got it to work, if anyone is interested the final code is here:
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
int main() {
// declaring variables
FILE *fp;
int charcount = 0, wordcount = 0, linecount = 1;
int charcount2 = 0, wordcount2 = 0, linecount2 = 1;
int character;
char first[50];
char second[50];
char ch[200];
// asking the user for the file names and scanning the names they enter as txt files
printf(" Enter the first file name: ");
scanf("%s", first);
strcat(first, ".txt");
printf(" Enter the second file name: ");
scanf("%s", second);
strcat(second, ".txt");
// opening the file stream
fp = fopen(first, "r");
// if the file cannot be reached, display error
if (fp == NULL) {
printf("File cannot be opened: %s\n", first);
return 0;
}
// reading and printing the file into the program
printf("\n---FIRST FILE---\n");
while (!feof(fp)) {
fgets(ch, 200, fp);
fputs(ch, stdout);
}
// counting the characters, words and lines until the program is finished
fseek(fp, 0, SEEK_SET);
while ((character = fgetc(fp)) != EOF) {
if (character == EOF)
break;
{
charcount++;
}
if (character == ' ' || character == '.')
{
wordcount++;
}
if (character == '\n')
{
linecount++;
}
}
// closing the stream
fclose(fp);
// printing the number of characters, words and lines
printf("\n Characters: %d \n Words: %d\n Lines: %d\n\n\n", charcount, wordcount, linecount);
//---------SECOND FILE----------//
// opening the stream
fp = fopen(second, "r");
// reading and printing the file into the program
printf("\n---SECOND FILE---\n");
while (!feof(fp)) {
fgets(ch, 200, fp);
fputs(ch, stdout);
}
// counting the characters, words and lines until the program is finished
fseek(fp, 0, SEEK_SET);
while ((character = getc(fp)) != EOF) {
if (character == EOF)
break;
{
charcount2++;
}
if (character == ' ' || character == '.')
{
wordcount2++;
}
if (character == '\n')
{
linecount2++;
}
}
// closing the stream
fclose(fp);
// printing the number of characters, words and lines
printf("\n Characters: %d \n Words: %d\n Lines: %d\n\n", charcount2, wordcount2, linecount2);
}
counting sample
#include <stdio.h>
#include <ctype.h>
typedef struct statistics {
size_t charcount, wordcount, linecount;
} Statistics;
Statistics count_cwl(FILE *fp){
size_t c = 0, w = 0, l = 0;
int ch;
char prev = ' ';
while((ch = getc(fp)) != EOF){
++c;
if(isspace(prev) && !isspace(ch)){
++w;//need to delete punctuation marks ?
}
if(ch == '\n'){
++l;
}
prev = ch;
}
if(prev != '\n')//There is no newline at the end of the file
++l;
return (Statistics){ c, w, l};
}
int main(void) {
char filename[50] = "test.c";
FILE *fp = fopen(filename, "r");
if (fp == NULL) {
printf("File cannot be opened: %s\n", filename);
return -1;
}
Statistics stat = count_cwl(fp);
fclose(fp);
printf("\nCharacters: %zu\nWords: %zu\nLines: %zu\n", stat.charcount, stat.wordcount, stat.linecount);
}

C program to ask for two separate files then displays number of characters, lines and words

I am writing a program to do this but have error messages. I have changed the fopen-s line to what it is now but this message appears after entering the two file names?
error message
here are no error messages that come up in visual studio but not sure if this is not the problem.
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
int main()
{
//setting names of ints and chars.
FILE *file_in;
int wordcount, linecount, charcount;
char letter;
char filename1[50];
char filename2[50];
//setting all counts to 0.
wordcount = 0;
linecount = 0;
charcount = 0;
//Gets the user to enter name of file, then puts it in string.
printf("\n Enter first text document\n");
gets_s(filename1);
printf("\n Enter second text document\n");
gets_s(filename2);
//opens then reads the first file.
fopen_s(&file_in, filename1, "r");
// counts the number of words, then lines, then letters in doc 1.
while ((letter = getc(file_in)) != EOF);
{
if (isspace(letter) && !isspace(getchar()))
{
wordcount++;
}
if (letter == '\n');
{
linecount++;
}
if (letter == '-')
{
charcount++;
}
}
//opens then reads the second file.
fopen_s(&file_in, filename2, "r");
// counts the number of words, then lines, then letters in doc 2.
while ((letter = getc(file_in)) != EOF);
{
if (isspace(letter) && !isspace(getchar()))
{
wordcount++;
}
if (letter == '\n');
{
linecount++;
}
if (letter == '-')
{
charcount++;
}
}
//displays the total on screen.
printf_s("Words:", wordcount, "\n");
printf_s("Letters", charcount, "\n");
printf_s("Lines", linecount, "\n")
}
fopen_s takes 3 arguments. First is pointer, to which you want to assign the file, second is filename and third is how you want to acces file ("r", "w", etc)
A few things I found to change here... This code worked for me:
#include "stdio.h"
#include "stdlib.h"
#include "ctype.h"
int main(int argc, char *argv[])
{
//setting names of ints and chars.
FILE *file_in;
int wordcount, linecount, charcount;
int letter;
char filename1[50];
char filename2[50];
//setting all counts to 0.
wordcount = 0;
linecount = 0;
charcount = 0;
printf("Enter first text document: ");
fgets(filename1, 50, stdin);
ch = filename1;
while(*ch != '\n')
ch++;
*ch = '\0';
printf("Enter second text document: ");
fgets(filename2, 50, stdin);
ch = filename2;
while(*ch != '\n')
ch++;
*ch = '\0';
//opens then reads the first file.
file_in = fopen(filename1, "r");
// counts the number of words, then lines, then letters in doc 1.
while((letter = fgetc(file_in)) != EOF)
{
if (letter == ' ')
{
wordcount++;
}
else if (letter == '\n')
{
linecount++;
}
else
{
charcount++;
}
}
//displays the total on screen.
printf("File 1...\n");
printf("Words: %d\n", wordcount);
printf("Letters: %d\n", charcount);
printf("Lines: %d\n", linecount);
//opens then reads the second file.
file_in = fopen(filename2, "r");
//reset counts
wordcount = 0;
linecount = 0;
charcount = 0;
// counts the number of words, then lines, then letters in doc 2.
while((letter = fgetc(file_in)) != EOF)
{
if (letter == ' ')
{
wordcount++;
}
else if (letter == '\n')
{
linecount++;
}
else
{
charcount++;
}
}
//displays the total on screen.
printf("File 2...\n");
printf("Words: %d\n", wordcount);
printf("Letters: %d\n", charcount);
printf("Lines: %d\n", linecount);
}

How to code my own version of tail unix command in C language?

I want to write my own code for tail Unix command but I am having a lot of trouble doing that. I am completely new to C language and apparently lost on how to fix my code. I am having number of problems regarding my code:
I am unable to read and print lines from text file in the if statements it is not printing any string from file when I run it don't know why?
Unable to print specific lines in if statement by taking user input as starting line and then printing till the End of File.
I am having trouble figuring out the right solution to my problems and debugging what problems there are in code.
I would really appreciate your help in figuring how to do all the above in my code. If someone can help make changes and get my code to work right.
#include <stdio.h>// for fopen, fscanf, fclose, fprintf
#include <stdlib.h>// for exit
#include <string.h>
int main(int argc, const char * argv[]){
printf("Opening file\n");
char filename[64]; // file attribute
strcpy(filename, argv[1]); //copy string from argv[1] to filename
printf("FILENAME: %s \n", filename);
FILE* fp; // file pointer
int ch, linestotal = 0, user;
char c[10000];
if(argv[2]){ //checking input argv[2]
user = atoi(argv[2]); // char to int
}
fp = fopen( filename, "r"); // file read
if(fp == NULL){ // verify file is opened
printf("Error opening file");
exit(1);
}
while(!feof(fp)) // check end of file
{
ch = fgetc(fp);
if(ch == '\n')
{
linestotal++; //Checking total lines inside file
}
}
printf("Total no. of lines: %d\n", linestotal );
printf("User input: %d\n", user );
printf("**********************\n");
if (!user && linestotal<= 10)
{
while ( (ch = fgetc(fp) ) != EOF)
printf("%c", ch);
fclose(fp);
printf("********************\n");
}if(!user && linestotal>10) { // to print 10 lines
for(int i = (linestotal-10); i <= (linestotal); i++)
{ c[i] = fgetc(fp);
printf("%c", c[i]);
}
fclose(fp);
printf("********************\n");
}if(user && user<linestotal) {
for(int i = (linestotal-user); i <= (linestotal); i++)
{ c[i] = fgetc(fp);
printf("%c", c[i]);
}
fclose(fp);
printf("********************\n");
}if(user && user>linestotal){
while ( (ch = fgetc(fp) ) != EOF)
printf("%c", ch);
fclose(fp);
printf("********************\n");
}else{
printf("Unable to read and print file \n");
}
printf("End of file");
return 0;
}

Resources