c - 用 C 编写的程序模拟 WC 命令不起作用

标签 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;
}

最佳答案

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

*lines++;

取消引用指针并增加它指向的值。单词和字符也是如此。

关于c - 用 C 编写的程序模拟 WC 命令不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21582680/

相关文章:

c - 它在C中创建了一个数组,当程序从内存中出来时会发生什么?

java - JNI : Get java. lang.UnsatisfiedLinkError 错误

c - 从c中的stdin读取字符串

eclipse - 以编程方式更改 eclipse RCP 命令的图标

git - 如何为git pull输入带密码的命令?

c - 如何识别没有订阅者的节点? (ZeroMQ)

c++ - 我被这段使用指针访问二维数组中的值的代码所困扰

c - 比较 C 中两个字符串的问题(段错误)核心转储

elasticsearch - 什么是 Elasticsearch 的 Nutch 1.10 爬行命令

c - 在 C 中声明字符数组的最佳实践