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);
}
Related
int main()
{
char ch;
int word_count = 0, in_word = 0;
char file_name[MAX_LEN];
/* Pointer for both the file*/
FILE *fpr, *fpw;
/* Opening file INPUT.txt in “r” mode for reading */
start:
printf("Enter a file name: ");
scanf("%s", file_name);
fpr = fopen(file_name, "r");
/* Ensure INPUT.txt opened successfully*/
if (fpr == NULL)
{
system("cls");
printf("Could not open the file %s\n", file_name);
goto start;
}
while ((ch = fgetc(fpr)) != EOF) {
{
printf("%c",ch);
}
if(ch == ' ' || ch == '\t' || ch == '\0' || ch == '\n') {
if (in_word) {
in_word = 0;
word_count++;
}
} else {
in_word = 1;
}
}
printf("In the file %s:\n", file_name);
printf("Number of words: %d.\n", word_count);
/* Opening file OUTPUT.txt in “w” mode for writing*/
fpw= fopen("OUTPUT.txt", "w");
/* Ensure OUTPUT.txt opened successfully*/
if (fpw == NULL)
{
puts("Output file cannot be opened");
}
/*Read & Write Logic*/
while ((ch = fgetc(fpr)) != EOF)
{
fputc(ch, fpw);
}
/* Closing both the files */
fclose(fpr);
fclose(fpw);
return 0;
}
Why is it not printing in the output.txt file? And how can I also print the words in the output file?
There must be a conflict between the while function before printing the input. Or maybe there is something reading before the output then having conflict with another one, when I remove the while function (count words) it shows the product in the output.
You read from fpr until you reach EOF, then try to read from it again.
You need to rewind the file to the beginning for the second fgetc() loop to produce anything.
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);
}
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);
}
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.
The problem: Use a c program to read a MIPS instruction file, output it to a second file (both are command line arguments) which contains the contents of the MIPS file, with line numbers. The second half is supposed to display a cross reference table, which details the identifier, the definition(a number), and the usage of that identifier, by line number, for any identifier used more than once.
Unfortunately, I've run aground, and the program not only doesnt seem to actually print anything, but it doesnt seem to make any files either. This is a bit of a last ditch effort, to see if anyone else can help me out.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/*Func line takes in a file, and places a line number at the beginning of every
non blank line */
void line(FILE *input, FILE *output) {
char a, c;
int lineNum = 0;
int startOfLine = 1;
char ch;
fprintf(output, "%d ", ++lineNum);
//copy the contents of the input file into the output file
do {
a = fgetc(input);
fputc(a, output);
c = getc(input);
if(a == '\n' && c != '\n') {
if(lineNum > 9)
fprintf(output, "%d ", ++lineNum);
else
fprintf(output, "%d ", ++lineNum);
}
ungetc(c, input);
} while (a != EOF);
printf("ran line: \n");
}
/* Func cross takes in a file, and finds each identifier, marks its definition, and every
use and returns that in the output file */
void cross(FILE *input, FILE *output) {
FILE *temp = fopen("temp.txt", "a+");
int lineNum = 0;
int startOfLine = 1;
char identifier[20][10];
char a, c, i;
int j, k, p;
int size=0;
int def[20];
int use[20][50];
char tempstr[80];
fprintf(output, "Identifier\tDefinition\t Use\n");
fprintf(temp, "%d ", ++lineNum);
//copy contents of input into a temp file
do {
a = fgetc(input);
fputc(a, temp);
c = getc(input);
if(a == '\n' && c != '\n') {
if(lineNum > 9)
fprintf(temp, "%d ", ++lineNum);
else
fprintf(temp, "%d ", ++lineNum);
}
ungetc(c, input);
} while (a != EOF);
fclose(temp);
fopen("temp.txt", "r");
j=0;
//checks to see if current line has an Identifier and if so saves it to an array
//along with the line number it was defined on
while(fgets(tempstr, 80, temp)) {
if(isalpha(tempstr[4]) || tempstr[4] == '_') {
sscanf(tempstr, "%d %[0-9_A-Z_a-z_]", &def[j], identifier[j]);
j++;
size++;
}
}
fclose(temp);
fopen("temp.txt", "r");
//checks for each identifier, on every line whether or not that identifier is used
while(fgets(tempstr, 80, temp)) {
char *tempNum;
sscanf(tempstr, "%s", tempNum);
int tempN = atoi(tempNum);
int n;
p=0;
for(n=0; n<size; n++) {
if(strstr(tempstr, identifier[n]) && tempN > def[n] && tempstr[4] != '#') {
use[n][p] = tempN;
p++;
}
}
}
//writes the identifier, definition, and uses to the file
for(k=0;k<size;k++) {
fprintf(output, "%s\t\t %d\t\t ", identifier[k], def[k]);
for(p=0; p<50; p++) {
if(use[k][p] != NULL && use[k][p] < lineNum && use[k][p] > def[k])
fprintf(output,"%d ", use[k][p]);
}
fprintf(output, "\n");
}
printf("ran cross: \n");
}
/*Func both returns the file with numbered lines and a cross reference table at the bottom of the file */
void both(FILE *input, FILE *output, char *outputName) {
FILE *lineFile = fopen("line.txt", "a+");
FILE *crossFile = fopen("cross.txt", "a+");
char ch;
line(input, lineFile);
cross(input, crossFile);
while( (ch = fgetc(lineFile)) != EOF)
fputc(ch, output);
fprintf(output, "\n\t\t\tCross Reference Table\n");
while( (ch = fgetc(crossFile)) != EOF)
fputc(ch, output);
fclose(output);
printf("ran both: \n");
}
int main(int argc, char * argv[]) {
FILE *input, *output;
output = fopen(argv[4], "a+");
char outputName[50];
strcpy(outputName, argv[4]);
//Error testing
if(argc > 5)
exit(1);
if(strcmp(argv[2], "-l") != 0 && strcmp(argv[2], "-c") != 0 && strcmp(argv[2], "-b") != 0) {
printf("Incorrect flag syntax... Exiting\n");
exit(1);
}
if((input = fopen(argv[3], "r+")) == NULL) {
printf("Input file could not be opened... Exiting\n");
exit(1);
}
else {
if(strcmp(argv[2], "-l") == 0) {
line(input, output);
}
else if(strcmp(argv[2], "-c") == 0)
cross(input, output);
else {
both(input, output, outputName);
}
}
printf("ran main: \n");
return 0;
}