1

WC コマンドをエミュレートするはずですが、readFile メソッドが機能していないようです。ポインターと関係があると思いますが、私はCにかなり慣れていないので、まだよく理解していません。手伝ってくれてどうもありがとう!ソースコードは次のとおりです。

/*
 *  This program is made to imitate the Unix command 'wc.'
 *  It counts the number of lines, words, and characters (bytes) in the file(s) provided.
 */

#include <stdio.h>

int main (int argc, char *argv[])
{
    int lines = 0;
    int words = 0;
    int character = 0;
    char* file;
    int *l = &lines;
    int *w = &words;
    int *c = &character;

    if (argc < 2) //Insufficient number of arguments given.
        printf("usage: mywc <filename1> <filename2> <filename3> ...");
    else if (argc == 2)
    {
        file = argv[1];
        if (readFile(file, l, w, c) == 1)
        {
            printf("lines=%d\t words=%d\t characters=%d\t file=%s\n",lines,words,character,file);
        }
    }
    else
    {
        //THIS PART IS NOT FINISHED. PAY NO MIND.
        //int i;
        //for(i=1; i <= argc; i++)
        //{
        //    readFile(file, lines, words, character);
        //}
    }
}

int readFile(char *file, int *lines, int *words, int *character)
{
    FILE *fp = fopen(file, "r");
    int ch;
    int space = 1;

    if(fp == 0)
    {
        printf("Could not open file\n");
        return 0;
    }

    ch = fgetc(fp);

    while(!feof(fp))
    {
        character++;
        if(ch == ' ') //If char is a space
        {
            space == 1;
        }
        else if(ch == '\n')
        {
            lines++;
            space = 1;
        }
        else
        {
            if(space == 1)
                words++;
           space = 0;
        }
        ch = fgetc(fp);
    }
    fclose(fp);
    return 1;
}
4

2 に答える 2

0

まず、while(!feof(fp))で問題が発生する可能性があります。多くの場合、推奨される方法ではなく、常に注意して使用する必要があります。

新しい機能で編集:

ファイル内の単語数を取得する方法の別の例を次に示します。

int longestWord(char *file, int *nWords)
{
    FILE *fp;
    int cnt=0, longest=0, numWords=0;
    char c;
    fp = fopen(file, "r");
    if(fp)
    {
        while ( (c = fgetc ( fp) ) != EOF )
        {
            if ( isalnum ( c ) ) cnt++;
            else if ( ( ispunct ( c ) ) || ( isspace ( c ) ) )
            {
                (cnt > longest) ? (longest = cnt, cnt=0) : (cnt=0);
                numWords++;
            }
        }
        *nWords = numWords;
        fclose(fp);
    }
    else return -1;

    return longest+1;
}

注:これは、最長の単語 も返しますは、たとえば、ファイルのすべての単語を文字列の配列に配置する必要がある場合に、割り当てるスペースを決定するときに役立ちます。

于 2014-02-05T17:13:39.803 に答える
0

readFile 関数では、ポインターを渡しています。したがって、行をインクリメントすると、ポインターが指す値ではなく、ポインターがインクリメントされます。次の構文を使用します。

*lines++;

これにより、ポインターが逆参照され、ポインターが指す値がインクリメントされます。言葉も性格も同じ。

于 2014-02-05T16:27:27.673 に答える