C 如何计算文件中的字符数?

C 如何计算文件中的字符数?,c,C,我已将一个文件的内容复制到另一个文件,并尝试获取行数、字数和字符数。我现在的代码显示了文件内容中的行数和字数。现在我需要显示字符数,但我不确定如何做到这一点。我在猜一个for循环?但我不确定 #include <stdlib.h> #include <string.h> #include <stdio.h> #define MAX_WORD_LEN 100 #define MAX_LINE_LEN 1000 #define ipsumFile "Lorem

我已将一个文件的内容复制到另一个文件,并尝试获取行数、字数和字符数。我现在的代码显示了文件内容中的行数和字数。现在我需要显示字符数,但我不确定如何做到这一点。我在猜一个for循环?但我不确定

#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#define MAX_WORD_LEN 100
#define MAX_LINE_LEN 1000

#define ipsumFile "Lorem ipsum.txt"
#define ipsumCopy "Lorem ipsum_COPY.txt"

int wordCount(FILE *fp);
int charCount(FILE *fp);
int sendContentTo(FILE *fp, FILE *out);
int getWordAt(FILE *fp, int pos, char *word);
int appendToFile(char *fileName, char *newText);

int main(void)
{
    FILE *fp, *fp2; //"file pointer"
    int ch; //place to store each character as read

    //open Lorem ipsum.txt for read
    if ((fp = fopen(ipsumFile, "r")) == NULL)
    {
        fprintf(stdout, "Can't open %s file.\n", ipsumFile);
        exit(EXIT_FAILURE);
    }

    //open Lorem ipsumCopy for writing
    if ((fp2 = fopen(ipsumCopy, "w+")) == NULL)
    {
        fprintf(stdout, "Can't open %s file.\n", ipsumCopy);
        exit(EXIT_FAILURE);
    }

    //print out and count all words in Lorem ipsum.txt
    int numOfWords = wordCount(fp);

    //print out and count all lines in Lorem ipsum.txt
    int numOfLines = sendContentTo(fp, stdout);

    //copy the content of Lorem ipsum.txt into a new file (ipsumCopy)
    numOfLines = sendContentTo(fp, fp2);

    fclose(ipsumFile);
    fclose(ipsumCopy);

    // close Lorem ipsum.txt
    if (fclose(fp) != 0)
        fprintf(stderr, "Error closing file\n");
    if (fclose(fp2) != 0)
        fprintf(stderr, "Error closing copy\n");
    return 0;
}

int sendContentTo(FILE *in, FILE *out)
{
    fprintf(stdout, "Performing file copy...\n\n");

    //start at the beginning of the file
    rewind(in);

    // array to hold one line of text up to 1000 characters
    char line[MAX_LINE_LEN];

    int lineCount = 0;

    // read one line at a time from our input file
    while (fgets(line, MAX_LINE_LEN, in) != NULL)
    {
        //send line we just read to output.
        fprintf(out, "%s", line);

        //count the lines
        lineCount++;
    }

    fprintf(stdout, "\nFinished line count.\n");
    fprintf(stdout, "Count is: %d.\n\n", lineCount);

    // Return how many text lines
    // we've processed from input file.
    return lineCount;
}

// Read content from file one character at a time.
// Returns number of total characters read from the file.
int charCount(FILE *fp)
{
    fprintf(stdout, "Performing char count...\n\n");

    rewind(fp);

    int charCount = 0;
    char ch;


    //print out each character, and return the
    // number of characters in the file.
    fprintf(stdout, "\nFinished character count. \n");
    fprintf(stdout, "Count is: %d. \n\n", charCount);

    return charCount;
}


// Read content from file one word at a time.
// Returns number of total words read from the file.
int wordCount(FILE *fp)
{
    fprintf(stdout, "Performing word count...\n\n");

    rewind(fp);

    char word[MAX_WORD_LEN];
    int wordCount = 0;

    while (fscanf(fp, "%s", word) == 1)
    {
        // Send entire word string
        // we just read to console
        puts(word);

        //count the word
        wordCount++;
    }

    fprintf(stdout, "\nFinished word count.\n");
    fprintf(stdout, "Count is: %d.\n\n", wordCount);
    return wordCount;
}
#包括
#包括
#包括
#定义最大单词长度100
#定义最大线长度1000
#定义ipsum文件“Lorem ipsum.txt”
#定义ipsumCopy“Lorem ipsum_COPY.txt”
int字数(文件*fp);
int字符数(文件*fp);
int sendcontento(文件*fp,文件*out);
int getWordAt(文件*fp,int pos,字符*word);
int appendToFile(char*fileName,char*newText);
内部主(空)
{
文件*fp,*fp2;//“文件指针”
int ch;//将每个字符存储为已读字符的位置
//打开Lorem ipsum.txt进行读取
if((fp=fopen(ipsumFile,“r”))==NULL)
{
fprintf(stdout,“无法打开%s文件。\n”,ipsumFile);
退出(退出失败);
}
//打开Lorem ipsumCopy进行书写
如果((fp2=fopen(ipsumCopy,“w+”)==NULL)
{
fprintf(stdout,“无法打开%s文件。\n”,ipsumCopy);
退出(退出失败);
}
//打印并计算Lorem ipsum.txt中的所有单词
int numOfWords=字数(fp);
//打印并计算Lorem ipsum.txt中的所有行数
int numOfLines=sendContentTo(fp,stdout);
//将Lorem ipsum.txt的内容复制到新文件(ipsumCopy)中
numOfLines=sendContentTo(fp,fp2);
fclose(ipsumFile);
fclose(ipsumpcopy);
//关闭Lorem ipsum.txt
如果(fclose(fp)!=0)
fprintf(stderr,“关闭文件时出错\n”);
如果(fclose(fp2)!=0)
fprintf(stderr,“关闭副本时出错\n”);
返回0;
}
int sendcontento(文件*in,文件*out)
{
fprintf(标准输出,“执行文件复制…\n\n”);
//从文件的开头开始
倒带(in);
//数组以容纳一行最多1000个字符的文本
字符行[MAX_line_LEN];
int lineCount=0;
//从输入文件中一次读取一行
while(fgets(直线,最大直线长度,英寸)!=NULL)
{
//将我们刚刚读取的行发送到输出。
fprintf(输出,“%s”,行);
//数数队伍
lineCount++;
}
fprintf(标准输出,“\n完成的行计数。\n”);
fprintf(标准输出,“计数为:%d.\n\n”,行计数);
//返回多少文本行
//我们已经从输入文件中处理了。
返回行计数;
}
//从文件中一次读取一个字符的内容。
//返回从文件中读取的总字符数。
int字符数(文件*fp)
{
fprintf(stdout,“正在执行字符计数…\n\n”);
倒带(fp);
int charCount=0;
char ch;
//打印出每个字符,并返回
//文件中的字符数。
fprintf(标准输出,“\n已完成字符计数。\n”);
fprintf(标准输出,“计数为:%d.\n\n”,字符计数);
返回字符数;
}
//从文件中一次读取一个单词的内容。
//返回从文件中读取的总字数。
int字数(文件*fp)
{
fprintf(stdout,“执行字数计数…\n\n”);
倒带(fp);
字符字[MAX_word_LEN];
int字数=0;
而(fscanf(fp,“%s”,word)==1)
{
//发送整个字串
//我们只是为了安慰而读书
放(字);
//数一数单词
字数++;
}
fprintf(标准输出,“\n已完成的字数。\n”);
fprintf(标准输出,“计数为:%d.\n\n”,字计数);
返回字数;
}

我认为以下方法可行:

void *cw(const char *fname)
{
    FILE *f = fopen(fname, "r");
    if (f == NULL) {
        fprintf(stderr, "fopen(%s): %s\n", fname, strerror(errno));
        exit(EXIT_FAILURE);
    }

    int bc = 0; /* bytes counter */
    int wc = 0 ; /* words counter */
    int nlc = 0; /* new lines counter */

    const int in_word_state = 0;
    const int out_word_state = 1;

    int state = out_word_state;

    int c = 0;
    for (;;) {
        c = fgetc(f);

        if (ferror(f) != 0) {
            perror("fgetc");
            goto error;
        }

        if (feof(f))
            break;

        if (c == '\n')
            nlc++;
        if (c == ' ' || c == '\t' || c == '\n')
            state = out_word_state;
        if (state == out_word_state) {
            state = in_word_state;
            wc++;
        }
        bc++;
    }

    if (fclose(f) == EOF) {
        perror("fclose");
        goto error;
    }

    printf("w: %d, c: %d, l:%d\n", wc, bc, nlc);

 error:
    if (f != NULL) {
        if (fclose(f) == EOF) {
            perror("fclose");
        }
    }
    exit(EXIT_FAILURE);
}

您不需要编写不同的函数来计算文件中的行数、字数和字符数。您可以逐个字符对文件进行单个解析,在解析时,为了将文件内容复制到另一个文件,您可以将字符写入另一个文件。你可以做:

#include <stdio.h>
#include <stdlib.h>

int count_and_copy(const char * ipsumFile, const char * ipsumCopy)
{
    unsigned int cCount = 0, wCount = 0, lCount = 0;
    int incr_word_count = 0, c;
    FILE *fp, *fp2;

    if ((fp = fopen(ipsumFile, "r")) == NULL)
    {
        fprintf(stdout, "Can't open %s file.\n", ipsumFile);
        exit(EXIT_FAILURE);
    }

    if ((fp2 = fopen(ipsumCopy, "w+")) == NULL)
    {
        fprintf(stdout, "Can't open %s file.\n", ipsumCopy);
        exit(EXIT_FAILURE);
    }

    while((c = fgetc(fp)) != EOF)
    {
            fputc(c, fp2); // write character c to the copy file
            cCount++; // character count
            if(c == '\n') lCount++; // line count
            if (c == ' ' || c == '\n' || c == '\t')
                    incr_word_count = 0;
            else if (incr_word_count == 0) {
                    incr_word_count = 1;
                     wCount++; // word count
            }
    }
    fclose (fp);
    fclose (fp2);
    printf ("Number of lines : %u\n", lCount);
    printf ("Number of words : %u\n", wCount);
    printf ("Number of characters : %u\n", cCount);
    return 0;
}
int main()
{
    /* Assuming, you want to count number of lines, words
     * and characters of file1 and copy the contents of file1
     * to file2.
     */
    count_and_copy("file1", "file2");
    return 0;
}
#包括
#包括
int count_和_copy(const char*ipsumFile,const char*ipsumCopy)
{
无符号整数计数=0,wCount=0,lCount=0;
int incr_word_count=0,c;
文件*fp,*fp2;
if((fp=fopen(ipsumFile,“r”))==NULL)
{
fprintf(stdout,“无法打开%s文件。\n”,ipsumFile);
退出(退出失败);
}
如果((fp2=fopen(ipsumCopy,“w+”)==NULL)
{
fprintf(stdout,“无法打开%s文件。\n”,ipsumCopy);
退出(退出失败);
}
而((c=fgetc(fp))!=EOF)
{
fputc(c,fp2);//将字符c写入复制文件
cCount++;//字符计数
if(c=='\n')lCount++;//行计数
如果(c=''| | c='\n'| | c='\t')
增量字数=0;
else if(增量字计数==0){
递增字数=1;
wCount++;//字数
}
}
fclose(fp);
fclose(fp2);
printf(“行数:%u\n”,lCount);
printf(“字数:%u\n”,wCount);
printf(“字符数:%u\n”,Account);
返回0;
}
int main()
{
/*假设,您要计算行数、字数
*和file1的字符,并复制file1的内容
*提交文件2。
*/
计数和拷贝(“文件1”、“文件2”);
返回0;
}

您应该在一个循环中进行字符、单词和行计数。逐个字符读取文件,始终增加字符计数器。如果字符是换行符,请增加行数。如果字符是一个单词分隔符(任何空格都可以),那么增加单词数。请特别注意将连续空格作为单个空格处理(使用单个标志可以轻松完成)。您可以使用现有库函数获取每个WOR的长度,这将允许您大部分保留现有代码,而无需将其重新构造为字符循环。