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