我需要编写一个程序,提示用户输入两个文本文件的名称,这两个文本文件将被读入并显示在屏幕上,然后是它们的统计信息,例如字符数、单词数和行数。我已经设法让除了统计部分之外的所有内容都正常工作。它们似乎没有计数,我认为这与我使用的 while 语句有关。任何帮助都会很棒:)
代码:
#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);
}
最佳答案
想象一下,您正在使用其中一个文本编辑器来打开文件,并且移动插入符号/光标是唯一的导航方式。您的第一个目标是浏览整个内容并显示它。这就是下面的循环的作用:
while(!feof(fp)){
fgets(ch, 200, fp);
puts(ch);
}
!feof(fp)
将光标移动到文件末尾,以便您可以阅读全部内容。
如果您必须计算字符数,那么您需要导航回文件中的某个位置。由于您想要整个 txt 的统计信息,因此您只需在第二个循环之前使用 rewind(fp)
或 fseek(fp, 0, SEEK_SET)
将光标向后移动到开始。
我建议使用fseek()
,因为它会清除文件末尾指示器。
仔细看看here .
关于c - 一个 C 程序读取两个文件并在屏幕上显示它们的统计信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40981549/