繁体   English   中英

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

[英]How do I count the number of characters in a file?

我已将一个文件的内容复制到另一个文件中,并且正在尝试获取行数、字数和字符数。 我现在拥有的代码显示文件内容中的行数和单词数。 现在我需要显示字符数,但我不确定如何做到这一点。 我在猜测 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;
}

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

#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;
}

我想以下方法会起作用:

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);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM