在C中编程以模拟WC命令不起作用

时间:2014-02-05 16:23:12

标签: c pointers command wc

它应该模拟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;
}

2 个答案:

答案 0 :(得分:0)

在readFile函数中,您传入指针。因此,当您增加线条时,您将增加指针,而不是指向的值。使用语法:

*lines++;

取消引用指针并递增它指向的值。与文字和字符相同。

答案 1 :(得分: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;
}

注意: 这也会返回最长的字,这在确定需要分配多少空间时非常有用。例如,将文件的所有单词放入字符串数组中。