函数是这样调用的,
printf("%d occurrences of %c in %s\n",
countoccurrences(argv[1], argv[1][0]),
argv[1][0], argv[1]);
这是我目前的职能:
/* countcharinfile
* input: char *filename, char c
* output: the number of occurrences of char c inside file filename
*/
int countoccurrences(char *filename, char c)
{
// count the number of occurrences of c in the file named filename
FILE *fp = fopen(filename,"r");
int ch,count=0;
while ((ch = fgetc(fp) != EOF))
{
if (ch == c)
count++;
}
return count;
}
当我运行程序时,./main 今天是美好的一天
我收到错误 Segmentation fault (core dumped)
最佳答案
看起来您在定义 main
之前就在使用函数 countoccurrences
。
在main
之前添加一个函数签名:
int countoccurrences(char *, char);
或者将函数本身移动到代码中 main
函数之前的位置。
还有:
- 您需要在
countoccurences
中将您的count
变量初始化为零,并且 - 在使用文件指针之前,您应该检查
fp != NULL
。如果无法打开文件,fopen
将返回 NULL。
When I run the program, ./main Today is a beutiful day
当您以这种方式运行您的程序时,您将向它传递 5 个参数,一个对应于您句子中的每个单词。查看您的函数和 main
中的函数调用:该函数需要一个文件名 来搜索,它应该是您程序的第一个参数,而不是要搜索的文本。第二个参数应该是要搜索的字符。
由于您没有检查 fopen
的返回值,您在此处的调用将导致问题,因为您可能没有有一个名为 Today 的文件 在工作目录中。
关于c - 如何计算文件中某个字符的出现次数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12665363/