簡體   English   中英

用C編寫的模擬WC命令的程序不起作用

[英]Program in C to Emulate WC command not working

它應該模擬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;
}

在您的readFile函數中,您傳入了指針。 因此,當增加行數時,就是在增加指針,而不是它指向的值。 使用語法:

*lines++;

這將取消引用指針並增加其指向的值。 單詞和字符相同。

首先,您可能會遇到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;
}

注意:這還會返回最長的單詞,例如,在需要以及何時需要將文件的所有單詞放入字符串數組時,確定要分配多少空間時,這將很有用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM