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

在您的 readFile 函数中,您正在传递指针。所以当你增加行时,你是在增加指针,而不是它指向的值。使用语法:

*lines++;

这会取消引用指针并增加它指向的值。文字和性格也一样。

于 2014-02-05T16:27:27.673 回答
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 回答